react中一个请求依赖于另一个请求的结果

react中发请求一般放在生命周期的componentDidMount事件中,但我现在有个需求是要发两个请求,第二个请求的参数是第一个请求的结果。

比如第一个请求的结果:state.res1 我如果把请求都直接放在componentDidMount中,第二个请求一开始是获取不到参数的。

我现在的做法是第一个请求除了更新state.res1,还会更新一个boolean:state.res1IsCompleted 标识,再把第二个请求放在componentDidUpdate中,然后根据res1IsCompleted这个标识判断要不要发起第二个请求。

但总觉得有点怪,如果我的请求依赖过多的话(因为现在在做工作流相关页面,设计的请求会很多),会有一堆的标识状态放在state中。

阅读 7k
4 个回答

js 是异步的,肯定拿不到。
给你推荐两个方法。

从你的描述中没有看到redux之类的东西,所以我假设你只有react,调用接口使用的是fetch.

  • 回调
componentDidMount() {
    fetch(url).then(data => data.json()).then(res= {
        fetch(url2, {body: {res}});
    })
}
  • Promise
componentDidMount() {
    const data1 = new Promise(resolve => {
        fetch(url).then(res => res.json()).then(data => resolve(data));
    });
    
    data1.then(data => {
        fetch(url2, {body: {data}});
    })
}

还有ES8提供的 async await .

写在请求的回调里不行吗?

直接把第二个请求放到第一个请求请求成功的回调函数里不就行了

我也碰到这个问题,不知道你是怎么解决的。我是这样写的:
getProdDetail()是获得这个商品的详情,
getRecList(obj)是获取推荐的商品,要根据当前商品的goods_id,
export const getProdDetail = (obj) => {

return (dispatch) => {
    let method = 'b2c.product2.app_productBaseInfo&';
    const params = {
        appid: 'webapp',
        version: '3.9.2',
        source: 'wap',
        token: '',
        ...obj
    };
    const url = `${rootUrl}${method}` + combParams(params);
    axios.get(url).then((response) => {
        const res = response.data.data;
        dispatch(getProdInfo(res.returndata));
        const goodObj = {
            goods_id: res.returndata.goods_id,
            type: 1
        };
        getRecList(goodObj, dispatch)
    })
};

};

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题