簡體   English   中英

將減速器從反應 redux 轉換為掛鈎

[英]convert reducer from react redux to hooks

我正在制作一個登錄/注冊應用程序。 我正在嘗試將基於 class 的組件的減速器轉換為與鈎子一起使用。 這是減速機:

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;
  }
}

如何將其轉換為減速器以用於鈎子功能組件?

這是我的登錄組件:

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, useSelectorreact-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);
  },[])

將您的操作導入組件並分派它。

調度(你的行動());

如果需要,您可以傳遞有效負載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM