【问题标题】:How do I call redux actions sequentially如何按顺序调用 redux 操作
【发布时间】:2019-03-18 06:44:33
【问题描述】:

我知道我需要使用 Promise,但无法将其放入代码中以实现我想要的。

所以我有 3 个 redux 操作:

getAllCoins()
getUserCoins()
setUserCoinPortfolio(a, b)

set 动作需要两个 get 动作的返回值,因此需要在这些函数完成后调用它。两个 get 可以同时触发。这就是我发起这两个电话的原因:

 refresh = async () => {
    this.setState({refreshing: true});
    this.props.getAllCoins();
    this.props.getUserCoins();
    this.setState({refreshing: false});
};

componentDidMount = () => {
    this.refresh();
}

我应该将这些组合成一个动作吗?我应该将它们分开,但如何构建调用?

非常感谢任何帮助

【问题讨论】:

标签: javascript reactjs redux promise react-redux


【解决方案1】:

当您使用 asyn 时,您可以等待前两个操作,一旦完成,您就可以调用 set.如下所示。

refresh = async () => {
    this.setState({refreshing: true});
    await this.props.getAllCoins();
    await this.props.getUserCoins();
    this.setState({refreshing: false});
};

refresh = async () => {
    this.setState({refreshing: true});
    await Promise.All([this.props.getAllCoins,this.props.getUserCoins]);
    this.setState({refreshing: false});
};

【讨论】:

  • 认为这是我正在寻找的,但需要使用这两个设置的值所以这应该工作:await this.props.getAllCoins() await this.props.getUserCoins() this.props.calculateUserCoinPortfolio(this.props.allCoins, this.props.userCoins)
  • 您可以将结果存储在从等待调用中返回的变量中,如下所示const [result1,result2] = await Promise.All([this.props.getAllCoins,this.props.getUserCoins]);
  • 所以如果我让我的 redux 操作返回一个值,我可以做到以上,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 2017-02-01
  • 1970-01-01
  • 2020-09-10
  • 2017-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多