1
我有一个文本输入域(通过Thunk)向服务器查询用户文本的有效性。由于这些请求可能会非常快速地发生,因此它们可能会以与发送时不同的顺序从服务器返回。因此,文本字段中的字符串可能会显示为无效,实际上它是有效的。Redux以不同的顺序处理网络响应
为了解决这个问题,我在收到服务器响应时执行检查 - 文本字段的当前内容与检查的内容相同吗?如果不是,请再次检查。我觉得应该有比查询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,
}
}