[英]Redux Thunk handling network responses in a different order
我有一個文本輸入字段,該字段(通過Thunk)向服務器查詢用戶文本的有效性。 由於這些請求可以非常快速地連續發生,因此它們可能以與發送時不同的順序從服務器返回。 因此,文本字段中的字符串實際上可能有效,但可能顯示為無效。
為了解決這個問題,當我收到來自服務器的響應時,我正在執行檢查-文本字段的當前內容是否與檢查的內容相同? 如果沒有,請再次檢查。 我覺得應該有比查詢DOM元素值更好的方法來處理這種情況。
我如何遵循從前到后的服務器請求?
export function updateUserCode(code) {
return dispatch => {
return dispatch(validateUserCode(code))
}
}
function validateUserCode(code) {
return dispatch => {
dispatch(updateCode(code))
return fetch(`/api/code/${code}`)
.then(response => response.json())
.then(json => dispatch(receiveValidatedCode(code, json)))
.catch(error => {Log.error(error)})
}
}
function receiveValidatedCode(code, data) {
const lastval = document.getElementById('usercode').value
if (code != lastval) {
// Code not the same as current value
// need to validate again
return updateUserCode(lastval)
}
if(data.success) {
return {
type: types.CODE_VALIDATED,
code: code,
}
}
return {
type: types.CODE_INVALID,
reason: data.reason,
}
}
在您的邏輯內部使用DOM確實很不理想。 我建議將最后輸入的文本字段值保留在Redux存儲中,並在reducer中執行檢查。
另外,如果當前輸入的值與上次解決的請求所驗證的值不同,則在重新驗證用戶輸入時也看不到任何意義。 請忽略此類響應,並且不要執行不必要的請求。
就代碼而言,您可以這樣做:
// actions
const requestValidation = value => ({ type: 'request-validation', value });
const receiveValidation = (value, result) => ({ type: 'receive-validation', value, result });
export const validateUserCode = code => dispatch => {
dispatch(requestValidation(code));
return fetch(`/api/code/${code}`)
.then(response => response.json())
.then(json => dispatch(receiveValidation(code, json)))
.catch(error => {Log.error(error)})
}
// reducer
export const validationReducer = (state = {}, action) => {
if (action.type === 'request-validation')
return ({ value: action.value, isValidating: true });
if (action.type === 'receive-validation' && state.value === action.value)
return ({ value: action.value, isValid: !!action.success });
return state;
};
那不是生產質量代碼,我不確定它是否有效,但是它反映了這個想法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.