以下是我的注册模式组件的摘要:
const auth = useSelector((state: RootState) => state.auth);
const authError = useSelector((state: RootState) => state.error);
const { isLoading, isAuthenticated, user, error, isSuccessful } = auth;
const dispatch = useDispatch();
const { register, handleSubmit, errors } = useForm();
console.log("useForm err", errors);
const { addToast } = useToasts();
useEffect(() => {
dispatch(removeError()); // cleaning previous authError message when modal opens
}, [isSuccessful]);
const onSubmit = (data) => {
const { email, username, password } = data;
dispatch({
type: REGISTER_USER_REQUEST,
data: { email, username, password },
});
if (isSuccessful) {
addToast(`Thank you for signing up! Now you can log in`, {
appearance: "success",
autoDismiss: true,
});
onClose();
} else {
return;
}
};
下面的auth reducer:
const initialState: AuthState = {
isLoading: false,
isAuthenticated: false,
isSuccessful: false,
user: null,
error: null,
};
export default (state = initialState, action) => {
return produce(state, (draft) => {
switch (action.type) {
case REGISTER_USER_REQUEST: {
draft.isLoading = true;
draft.isSuccessful = false;
draft.error = null;
break;
}
case REGISTER_USER_SUCCESS: {
draft.isLoading = false;
draft.isSuccessful = true;
draft.error = null;
break;
}
case REGISTER_USER_FAILURE: {
draft.isLoading = false;
draft.isSuccessful = false;
draft.error = action.error;
break;
}
我注意到填写完注册表单并单击提交按钮(期望 isSuccessful 更改为 true ),但 isSuccessful 状态仍然为 false ,然后我必须再次单击Submit按钮,然后由于状态在React中异步工作,因此它变为 true ,因此我将其放入useEffect的依赖关系但没有运气,仍然无法正常工作。 我有什么想念的吗?
答案 0 :(得分:0)
您应该将此方块移入效果:
useEffect(() => {
if (isSuccessful) {
addToast(`Thank you for signing up! Now you can log in`, {
appearance: "success",
autoDismiss: true,
});
onClose();
}
}, [isSuccessful])
在派遣将在某个时候更改状态的操作后立即检查isSuccessful
的值,这还为时过早。