我有一个登录表单,我想处理它的提交功能并通过redux更新处理。
Login.js:
const Login = (props) => {
const dispatch = useDispatch();
const isUserExists = useSelector((state) => state.auth.isUserExists);
const handleSubmitForm = (vals) => {
dispatch(isUserExistsByPhoneNumber("Login", vals)).then(() =>
props.navigation.navigate(isUserExists ? "VerifyAuth" : "Signup", {
vals: vals,
sentFrom: "Login",
})
);
};
LoginForm.js:
const LoginForm = (props) => {
const handleFormSubmit = () => {
props.submitForm(values);
};
const [values, handleChange, handleSubmit] = useForm(handleFormSubmit);
return (
<View>
<Input
name="phoneNumber"
value={values.phoneNumber || ""}
onChange={(name, value) => handleChange(name, value)}
label="Phone Number"
keyboardType="number-pad"
/>
<Button
mode="outlined"
onPress={handleSubmit}
loading={props.submitting}
disabled={props.submitting}>
Login
</Button>
</View>
);
};
AuthActions.js:
export const isUserExistsByPhoneNumber = (sentFrom, phoneNumber) => {
return (dispatch) => {
dispatch({ type: authTypes.GET_IS_USER_EXISTS_REQUEST });
return authService
.checkIfUserExists(sentFrom, phoneNumber)
.then((response) => {
dispatch({ type: authTypes.GET_IS_USER_EXISTS_SUCCESS });
dispatch(setIsUserExists(response));
})
.catch((errors) => {
dispatch({ type: authTypes.GET_IS_USER_EXISTS_ERROR, payload: errors });
});
};
};
该代码不起作用,仅仅是因为在Login.js
处分派之后的“ .then”没有等待分派完成才继续进行。
如何解决此问题,并且仅在调度完成后读取isUserExists数据?
如果我使用useEffect进行操作,是否需要创建“ isDoneDispatching”道具并仅在该道具更新时进行导航?
谢谢。
答案 0 :(得分:0)
您将导航移至useEffect
处在正确的轨道上。
但是您似乎没有将values
存储在redux存储中。
因此,您必须将它们存储在组件状态中,才能将它们传递给导航逻辑
const Login = (props) => {
const dispatch = useDispatch();
const isUserExists = useSelector((state) => state.auth.isUserExists);
// store values in component state
const [values, setValues] = useState(null);
const [allowNavigate, setAllowNavigate] = useState(false);
const handleSubmitForm = (vals) => {
// store values in component state since you do not store them in redux state
setValues(vals);
dispatch(isUserExistsByPhoneNumber("Login", vals)).then(() => {
setAllowNavigate(true);
});
};
useEffect(() => {
if (allowNavigate) {
props.navigation.navigate(isUserExists ? "VerifyAuth" : "Signup", {
vals: values,
sentFrom: "Login",
});
}
}, [allowNavigate, isUserExists, values]); // track values and isUserExists change
// ...
};