【发布时间】:2021-11-06 17:05:04
【问题描述】:
我正在使用 React Native 和 Redux。在 Redux 的初始状态下,emailExists 设置为null:
const INITIAL_STATE = {
// ...
emailExists: null,
};
注册用户时。首先,我通过向服务器发送请求来检查用户是否已经存在,如果用户已经存在,我会显示一个 toast。
const registerUser = (values, actions) => {
checkEmail(values.userEmail); // takes time to get result of `emailExists`
if (emailExists) { // `emailExists` is now `null` couldn't wait for response
toastRef.current.show("Email already exists!");
return;
}
}
checkEmail 代码如下:
function checkEmail(data) {
return (dispatch) => {
return api_request
.post("register/check/email", { email: data })
.then((res) => {
dispatch(emailExists(res.data.exists));
dispatch(authError("Email already exists"));
})
.catch((err) => {
console.log(`err`, err);
});
};
}
在调度dispatch(emailExists(res.data.exists)); 之后,emailExists 将是true 或false,但问题是由于请求需要时间从服务器获取数据,所以在第一次加载应用程序时总是设置emailExists到null。这意味着以下条件在第一次加载时总是错误的:
if (emailExists) {
toastRef.current.show("Email already exists!");
return;
}
function emailExists(payload){
return {
type: userConstants.EMAIL_EXISTS,
emailExists: payload
}
}
我该如何解决这个问题?
谢谢你
【问题讨论】:
标签: reactjs react-native asynchronous redux async-await