首页 > 解决方案 > 在 react-redux white 尝试注册时遇到问题处理错误

问题描述

在此处输入图像描述在这里,我有注册用户的组件代码并检查错误。起初错误为空。

      let error = useSelector((state) => state.authReducer.error);

      const checkErrorLoading = () => {        
        console.log("If error found");  //At first it gives null, but on backend there is error
        toast.error(error);
        console.log(loading, error);
      };

      const handleSubmit = async (e) => {
        if (isSignup) {
          dispatch(signup(form, history));
          checkErrorLoading();
        } else {
          dispatch(signin(form, history));
          checkErrorLoading();
        }
      };

现在在我的 singupForm 中,我提供了错误的输入或错误的数据。后端给了我完全没问题的错误。

ISSUE => 但是当我点击登录按钮时。第一次尝试它不提供任何错误消息。在第二次尝试后它工作正常,但不是第一次尝试。第一次尝试它给我错误值NULL,而仍然有错误

这是我的行动。

    export const signup = (formData, history) => async (dispatch) => {
      try {
        const res = await api.signUp(formData);
        dispatch({ type: authConstants.AUTH_REQUEST });
        if (res.status === 200) {
          const { data } = res;
          console.log(data);
          dispatch({
            type: authConstants.AUTH_SUCCESS,
            payload: data,
          });
        }
        console.log(res.status);
        history.push("/");
      } catch (error) {
        console.log(error.response);
        dispatch({
          type: authConstants.AUTH_FAILURE,
          payload: error.response.data.error,
        });
      }
    };

而不是减速机。

    const initialState = {
      authData: null,
      error: null,
      loading: false,
    };

    const authReducer = (state = initialState, action) => {
      switch (action.type) {
        case authConstants.AUTH_REQUEST:
          return { ...state, loading: true, error: null };

        case authConstants.AUTH_SUCCESS:
          localStorage.setItem("profile", JSON.stringify({ ...action?.payload }));
          return { ...state, authData: action?.data, loading: false, error: null };

        case authConstants.AUTH_FAILURE:
          console.log(action.payload);
          return { ...state, loading: false, error: action.payload };
      }

标签: javascriptreactjsreduxreact-redux

解决方案


对于这种情况,您应该使用useEffect而不是本地函数 ( ):checkErrorLoading

    useEffect(() => {        
      console.log("If error found");
      toast.error(error);
      console.log(loading, error);
    },[error]);

目前你所做的是创建局部函数,该闭包error变量,最初是null+ 状态是异步更新的,所以你不能在调度后立即执行函数(即使变量不会被关闭,你也不会在那里有新的状态)


推荐阅读