2017-04-06 14 views
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, 
    } 
} 

回答

2

在你的逻辑中弄乱DOM,确实不太理想。我建议在Redux商店中保留上次输入的文本字段值并在减速器中执行检查。

此外,如果当前输入的值与上次解析请求验证的值不同,我不会在重新验证用户输入时看到任何意见。只要忽略这些回应,不要执行不必要的要求。

在代码方面,你可以那样做:

// 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; 
}; 

这不是生产质量的代码,我不肯定的事件,如果它的工作原理,但它反映的概念。