javascript - 在 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 };
}
解决方案
对于这种情况,您应该使用useEffect
而不是本地函数 ( ):checkErrorLoading
useEffect(() => {
console.log("If error found");
toast.error(error);
console.log(loading, error);
},[error]);
目前你所做的是创建局部函数,该闭包error
变量,最初是null
+ 状态是异步更新的,所以你不能在调度后立即执行函数(即使变量不会被关闭,你也不会在那里有新的状态)
推荐阅读
- android - 如何通过滚动仅显示微调器中的前 3 个项目和其他项目?
- reactjs - IE11 中的故事书有问题。“未定义弱集”
- java - AWS texttract 提取元数据和置信度分数
- outlook-web-addins - Outlook 加载项对话框的事件处理程序失败
- javascript - 为什么我的代码没有改变 div 颜色?
- html - 浏览器渲染问题
- cassandra - 如何使用 Java 跟踪 Cassandra 表中的更改
- c# - 如何在 C# Web API 中发布 IFormFile?
- remote-debugging - IIS 中的 ASP.NET Web API 远程调试中未命中断点
- java - Okhttp 帖子返回 null