Redux Thunk以不同的顺序处理网络响应

时间:2017-04-06 11:20:46

标签: javascript redux redux-thunk fetch-api

我有一个文本输入字段(通过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,
    }
}

1 个答案:

答案 0 :(得分:2)

在逻辑中弄乱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; 
};

这不是生产质量代码,我不确定它是否有效,但它反映了这个想法。