反应useReducer不更新状态

时间:2020-10-02 00:35:30

标签: javascript reactjs react-hooks use-reducer

当用户登录失败时,我正在使用int divideBy(int number, int timesIn) { int count = 0; while (number >= timesIn) { number = number - timesIn; count++; println(number); } return count; 更新useReducer。我已经阅读了许多解决方案,据说errorsState是异步的,我知道,所以我将dispatch放在console.log里面以查看useEffect的变化,但不幸的是没有改变。这是我的代码

Login.jsx

errorsState

这里是提取函数export default function Login({ userProps }) { // // some variables and state // const { loading, user } = useLogin({ email: state.email }, state.submitted) const [errors, dispatch] = useReducer(errorsReducer, errorsState) useEffect(() => { console.log("errors", errors) // it won't triggered because errors state didn't updating from UseLogin }, [errors]) return content }

AuthAction.js

useLogin

我尝试将export const useLogin = (data, submitted) => { const [state, dispatch] = useReducer(userReducer, userState) const [errors, errorsDispatch] = useReducer(errorsReducer, errorsState) useEffect(() => { if (!submitted) return dispatch({ type: USER_ACTIONS.MAKE_REQUEST, }) ticketApi.login(data).then(({ res, status }) => { if (status !== "failed") { // Save to local storage const { token } = res // set token to local storage localStorage.setItem("jwtToken", token) // Set token to Auth Header setAuthToken(token) // decode token to get user data with jwt-decode const decoded = jwt_decode(token) // set current user return dispatch({ type: USER_ACTIONS.GET_USER, payload: decoded, }) } dispatch({ type: USER_ACTIONS.END_REQUEST, }) return errorsDispatch({ type: ERRORS_ACTIONS.GET_ERRORS, payload: res.response.data, }) }) }, [submitted]) return state } 放在console.log内以查看响应,这很好。 那我哪里出错了?

1 个答案:

答案 0 :(得分:1)

useReducer使您可以更好地管理复杂状态,它不是状态容器,您要做的是创建2个不同的状态,一个在useLogin内,另一个在{{1 }}组件,请从您的Login钩子返回errors,以便Login组件可以看到它。

登录

useLogin

useLogin

export default function Login({ userProps }) {
  //
  // some variables and state
  //
  const { loading, user, errors } = useLogin({ email: state.email }, state.submitted)

  useEffect(() => {
    console.log("errors", errors)
  }, [errors])

  return content
}