等待异步提交表单调度完成,然后继续下一行



我有一个登录表单,我想处理它的提交功能,并通过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 });
});
};
};

代码不起作用,原因很简单;。那么";在CCD_ 4处的调度没有在继续之前等待调度完成之后。

如何修复此问题,并仅在调度完成后读取isUserExists数据?

如果我用useEffect来做,我需要创建";isDoneDispatching";道具并只在道具更新时导航?

谢谢。

您将导航移动到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
// ...
};

相关内容

  • 没有找到相关文章

最新更新