等待多个异步调用完成,然后再进行React渲染

时间:2018-09-05 14:14:02

标签: reactjs react-redux

我有一个组件,它依赖于呈现内容之前要异步检索的数据。如果数据尚不可用,则渲染功能将改为返回Loader组件:

    if (this.state.loading) {
        return <Loader />;
    }

在调用返回数据后,加载状态设置为false:

componentDidMount() {

        ExternalComponent.fetchData().then(response => {
            this.setState({
                loading: false,
                data: response
            });
        });
}

这行得通,但是如果我想并行添加另一个异步获取调用怎么办?在将“加载”状态设置为false之前,我该如何正确地等待两者完成?

3 个答案:

答案 0 :(得分:5)

使用Promise.all

componentDidMount() {
  const fetchData1 = ExternalComponent.fetchData()
  const fetchData2 = AnotherExternalComponent.fetchData()

  Promise.all([ fetchData1, fetchData2 ]).then((responses) => {
      this.setState({
          loading: false,
          data: responses[0]
      });
  });
}

答案 1 :(得分:2)

我认为您在这里有多个选择,但是如果您已经使用taskSelected$,为什么不将逻辑移到那里?借助ResponsiveNavigationComponent,您可以在操作创建者中执行异步操作并使用全局流程状态。

相关的减速器

redux

相关动作:

redux-thunk

然后您的动作创建者将是这样的:

const initialState = 0;

const progressReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.INCREMENT_PROGRESS:
      return state + 1;
    case types.DECREMENT_PROGRESS:
      return Math.max(state - 1, 0);
    default:
      return state;
  }
};

这是异步函数的示例,但是您当然可以使用promise。 当您要进行多个异步操作时,只需触发您的操作创建者,他们就可以将过程增加一。在您的组件中,您将检查export const incrementProgress = () => ({ type: types.INCREMENT_PROGRESS }); export const decrementProgress = () => ({ type: types.DECREMENT_PROGRESS }); 的状态是否大于0或类似export const anAsyncFunction = () => async dispatch => { dispatch(incrementProgress()); try { const someResponse = await someAsyncJob(); dispatch(anAction(someResponse)); } catch (error) { errorHandler(error); } finally { dispatch(decrementProgress()); } }; 而不是显示正在加载的组件。

答案 2 :(得分:0)

为简单起见,您可以具有两个或多个加载标志,如下所示:

if (this.state.loading1 || this.state.loading2) {
    return <Loader />;
}
相关问题