【问题标题】:How to create async/await structure for two redux actions?如何为两个 redux 操作创建 async/await 结构?
【发布时间】:2020-01-22 16:15:34
【问题描述】:

我对按钮更改功能有两个相互依赖的操作。我想要做的是将这两个函数放在 async/await 结构中,以便在 update_other_filter 操作结束后,我将能够运行 getTotalData 操作。像下面的结构运行它实际上不会以正确的方式更新状态。我在 getTotaldata 中发送以前的状态(在 update_other_filter 之前)。

你们可能会说,当它解决时,我必须在 update_other_filter 操作中调度 getTotalData。但在我的项目的这种状态下,我似乎无法改变任何东西。我对 async/await 和 promises 的概念不太了解,所以我只想在我的 react 组件中创建 async/await 函数,而不是在 onChange 函数中调用它。有没有办法做到这一点?

onChange = {(event) => {
      this.props.setSpinner()
      //this update filter function updates filter which will be sent to server in getTotalData action
      this.props.update_other_filter(true,"website",!event.target.checked)
      //this action should wait for update_other_filter to end than it has correct parameters to send to server
      this.props.getTotalData(this.props.totalFilters, apiUrl)
      }

【问题讨论】:

    标签: javascript reactjs redux async-await react-redux


    【解决方案1】:
    async onChange = {(event) => {
       this.props.setSpinner()
       await this.props.update_other_filter(true,"website",!event.target.checked)
       this.props.getTotalData(this.props.totalFilters, apiUrl)
    }
    

    【讨论】:

    • Hocam çok teşekkürler
    【解决方案2】:
    // I will make function wait that needs for dependent function and also add some error handling.
    
    async onChange = {(event) => {
       this.props.setSpinner()
       try
       {
       await this.props.update_other_filter(true,"website",!event.target.checked)
       this.props.getTotalData(this.props.totalFilters, apiUrl)
       }
       catch(e)
       {
         thorw e;
        }
    }
    

    【讨论】:

    • 这实际上不起作用。 onChange 是输入 html 字段的功能。我可以使 onChange 或 onClick 函数异步吗?
    猜你喜欢
    • 2018-04-13
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 2020-06-22
    • 2019-06-03
    • 2021-10-25
    • 2018-09-10
    相关资源
    最近更新 更多