我正在使用React Native和Redux。在Redux的初始狀態下emailExists被設定為null:
const INITIAL_STATE = {
// ...
emailExists: null,
};
當注冊用戶時。首先,我通過向服務器發送請求來檢查用戶是否已經存在,如果用戶已經存在,我將顯示一個祝酒詞。
const registerUser = (values, actions)=> {
checkEmail(values.userEmail); //需要時間獲得`emailExists`的結果。
if (emailExists) { // `emailExists`現在是`null`無法等待回應。
toastRef.current.show("Email already exists!")。
return;
}
checkEmail代碼看起來像這樣:
function checkEmail(data) {
return (dispatch) => {
return api_request
.post("register/check/email"/span>, { email: data })
.then((res) =>/span> {
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("電子郵件已經存在!")。
return。
function emailExists(payload){
return {
type: userConstants.EMAIL_EXISTS,
emailExists: payload
}
我如何解決這個問題?
謝謝你
uj5u.com熱心網友回復:
你可以像這樣修改函式,以獲得預期的結果。
function checkEmail(data,callback){
return (dispatch) => {
return api_request
.post("register/check/email"/span>, { email: data })
.then((res) =>/span> {
// dispatch(emailExists(res.data.exists)); // You don't need this redux approach now because it will take time and will give you the same error.
dispatch(authError("Email already exists"))。
callback && callback(res.data.exists) // I am assuming here you got the response that email alreay exists and its value is true..
})
.catch((err) => {
console.log(`err`, err)。
});
};
}
現在,當API請求完成,你得到回應時,得到回呼。
const registerUser=(values, actions)=> {
const callback = (isEmailExists) => {
//Here you will get the value of the checkemail API (true/false)
/Now do any action in this block of functions[/span]。
if (isEmailExists) {
toastRef.current.show("電子郵件已經存在!")。
return;
}
}
checkEmail(values.userEmail,callback)。
}
uj5u.com熱心網友回復:
Mantu的回答是一種解決方案。對于這個用例,我更愿意使用async/await。 你將需要從承諾中回傳電子郵件是否存在,否則即使你等待你的checkEmail動作完成,當你訪問它時,emailExists也不會是最新的(因為使用useSelector將不得不重新渲染組件以反映商店中的更新)。
如果你不想從承諾中回傳屬性,你將需要通過store.getState()從商店同步獲取值:
標籤:dispatch()回傳動作創建者所回傳的任何函式。所以在這種情況下,你將回傳一個承諾,這意味著你可以等待你的dispatch(checkEmail(values.userEmail))/code>呼叫。
const registerUser = async(values, actions)=> {
const emailExists = await checkEmail(values.userEmail)。
if (emailExists) {
toastRef.current.show("電子郵件已經存在!")。
return。
}
function checkEmail(data) {
return (dispatch) => {
return api_request
.post("register/check/email"/span>, { email: data })
.then((res) =>/span> {
dispatch(emailExists(res.data.exists) )。)
dispatch(authError("Email already exists"))。
return res.data.exists。
})
.catch((err) =>/span> {
console.log(`err`, err)。
});
};
}
const registerUser = async(values, actions)=> {
await checkEmail(values.userEmail)。
const emailExists = selectEmailExists(store.getState())。
if (emailExists) {
toastRef.current.show("電子郵件已經存在!")。
return;
}
