【问题标题】:React concurrent API calls响应并发 API 调用
【发布时间】:2018-11-16 22:50:06
【问题描述】:

所以,我当前的代码如下所示:

组件:

requestDescriptions(params, bothGender) {
    if (bothGender) {
        // men request
        params.gender = 'men';
        this.props.getDescriptions(params);
        // women request
        params.gender = 'women';
        this.props.getDescriptions(params);
    } else {
        this.props.getDescriptions(params);
    }
}

我的操作如下所示:

export function getDescriptions(params = { brand: null, category: null, gender: null }) {
return (dispatch) => {
    dispatch(requestDescription());
    return request
        .get(`${getApiUrl()}plp?${QueryString.stringify(params)}`)
        .end((err, res) => {
            if (err && res.statusCode !== 404) {
                ...
            }
            if (res.statusCode === 404) {
                // HERE: 
                console.log(params.gender); 
                return dispatch(receiveEmptyDescription(params));
            }
            return dispatch(receiveDescription(res.body));
        });
};

}

所以直到现在,我还没有注意到这个错误,但是当我开始测试两个 API 调用都返回 404 的场景时才注意到。

错误是对同一端点进行并发调用会覆盖我的参数。当 API 返回 200 时,我看不到问题所在。但是现在当我测试返回 404 时,我可以清楚地看到问题所在。

我遇到的问题在这里:

this.props.getDescriptions(params);
params.gender = 'women';

如果我在我的操作 (//HERE) 中检查控制台日志,在这两种情况下 params.gender 都会显示 'women',即使第一次应该是 'men'

我想这可以通过承诺来解决?

如果我不够清楚,请告诉我。

【问题讨论】:

    标签: javascript reactjs redux promise


    【解决方案1】:

    问题并不在于您正在发出并行请求,或者您正在获取 HTTP2XX 或 HTTP4XX。

    您总是看到gender 等于'women' 的原因是您对两个请求都使用了相同的对象实例,即params

    发生的情况是您将params.gender 设置为'men',触发第一个请求,将params.gender 设置为'women',触发第二个请求。

    上述所有步骤在任何请求完成之前同步发生。

    这意味着早在任何请求完成之前,params.gender 就已经等于 'women'

    只需向每个操作发送不同的对象。

    requestDescriptions(params, bothGender) {
        if (bothGender) {
            // men request
            this.props.getDescriptions({ ...params, gender: 'men' });
    
            // women request
            this.props.getDescriptions({ ...params, gender: 'women' });
        } else {
            this.props.getDescriptions(params);
        }
    }
    

    既然你已经在使用 Redux,你应该知道变异是 baaaad ?

    【讨论】:

      猜你喜欢
      • 2015-08-13
      • 2018-02-17
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      相关资源
      最近更新 更多