【问题标题】:Redux-Thunk - how to wait for action creator to finishRedux-Thunk - 如何等待动作创建者完成
【发布时间】:2019-03-20 03:51:50
【问题描述】:

我有这个动作创建者:

type LoadOpenRequestsResult = ThunkAction<
  Promise<void>,
  IRootState,
  undefined,
  LoadOpenRequestsActions
>;

export const loadOpenRequests: ActionCreator<LoadOpenRequestsResult> = () => {
  [...]
};

我在我的组件中使用它:

public componentDidMount() {
  this.props.loadOpenRequests();
}

我使用 mapDispatchToProps 的对象版本连接我的 React 组件,如下所示:

export default connect(
  mapStateToProps,
  { loadOpenRequests }
)(MaintenanceOpenListScreen);

我想在异步操作完成后做一些事情,像这样:

public componentDidMount() {
  await this.props.loadOpenRequests();
  doSomethingWhenThisAsyncIsDone();
}

this.props.loadOpenRequests(); 不是 Promise。

这是否意味着我不能使用 mapDispatchToProps 的对象版本?

【问题讨论】:

    标签: redux react-redux redux-thunk


    【解决方案1】:

    我在这里找到了解决方案:https://github.com/reduxjs/redux-thunk/issues/213#issuecomment-428380685

    基本上答案是肯定的,不能使用mapDispatchToProps的对象版本。您必须像这样使用函数版本:

    public componentDidMount() {
      this.props.loadOpenRequests().then(() => doSomethingWhenThisAsyncIsDone());
    }
    
    [...]
    
    const mapDispatchToProps = (
      dispatch: ThunkDispatch<IRootState, undefined, Action>
    ) => ({
      loadOpenRequests: () => dispatch(loadOpenRequests()),
    });
    
    export default connect(
      mapStateToProps,
      mapDispatchToProps
    )(MaintenanceOpenListScreen);
    

    【讨论】:

      猜你喜欢
      • 2020-11-21
      • 2016-10-24
      • 2017-06-15
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 2019-09-22
      • 2020-05-23
      • 2017-04-18
      相关资源
      最近更新 更多