程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了将 reducer 从 react redux 转换为 hooks大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决将 reducer 从 react redux 转换为 hooks?

开发过程中遇到将 reducer 从 react redux 转换为 hooks的问题如何解决?下面主要结合日常开发的经验,给出你关于将 reducer 从 react redux 转换为 hooks的解决方法建议,希望对你解决将 reducer 从 react redux 转换为 hooks有所启发或帮助;

我正在制作一个登录/注册应用程序。我正在尝试将基于类的组件的 reducer 转换为与钩子一起使用。这是减速器:

import { SET_CURRENT_USER,user_LOADING } from "../actions/types";

const isEmpty = require("is-empty");

const initialState = {
  isAuthenticated: false,user: {},loading: false
};

export default function(state = initialState,action) {
  switch (action.typE) {
    case SET_CURRENT_USER:
      return {
        ...state,isAuthenticated: !isEmpty(action.payload),user: action.payload
      };
    case user_LOADING:
      return {
        ...state,loading: true
      };
    default:
      return state;
  }
}

如何将其转换为 reducer 以用于 hooks 功能组件?

这是我的登录组件:

function Login (props) {
 
      const [email,setEmail] = useState("");
      const [password,setpassword] = useState("");
      const [errors,setErrors] = useState([]);
 useEffect(() => {
    if (props.auth.isAuthenticated) {
      props.history.push("/dashboard");
    }
  });
useEffect(() => {
    if (props.auth.isAuthenticated) {
      props.history.push("/dashboard");
    }
  },[props.auth]);
const onsubmit = e => {
    e.preventDefault();

    const userData = {
      email: email,password: password
    };

    props.loginUser(userData);
  };
 form data....

解决方法

您可以使用 useDispatch,useSELEctor 中的 react-redux

import { useDispatch,useSELEctor } from 'react-redux';

const dispatch = useDispatch();

const user = useSELEctor(getUser); 
// you can pass your SELEctor function to useSELEctor(state => state.user)

useEffect Hook 中,您可以使用 dispatch() 来调度您的操作

 useEffect(() => {
    dispatch(your action goes herE);
  },[])
,

将您的操作导入到您的组件中并分派它。

dispatch(yourAction());

如果需要,您可以传递有效负载。

大佬总结

以上是大佬教程为你收集整理的将 reducer 从 react redux 转换为 hooks全部内容,希望文章能够帮你解决将 reducer 从 react redux 转换为 hooks所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。