【问题标题】:How to call a function before and then depending on data update state-React-redux如何根据数据更新 state-React-redux 前后调用函数
【发布时间】:2019-04-13 10:17:11
【问题描述】:

我有一个下拉菜单来选择调用 saga 并且必须使用相同的组件。 saga 被调用,唯一没有发生的是设置状态在 saga 调用之前更新,因此组件永远不会更新数据。

            recievedChangeValue=(selectVal)=>{
                console.log(selectVal)
                if(selectVal==='Yearly'){
                     this.props.getYearlySales() **//call to saga**
                     this.setState({salesData:this.props.yearlySales}) **//it updates before the called saga ends**                         
                 }
                if(selectVal==='Decade'){ 
                    this.props.getSales()**//call to saga**
                    this.setState({salesData:this.props.dataSales})   **//it updates before the called saga ends**                                           
                }
            }

我知道回调,但这里的状态必须在 saga 调用之后才更新。从过去的一天开始,我一直在努力,我不知道必须做什么。任何帮助表示赞赏。请让我知道我哪里出错了。

【问题讨论】:

    标签: react-redux redux-saga


    【解决方案1】:

    您不能在组件中等待 saga 完成,因为 this.props.getSales 并没有真正调用 saga - 它只是调度一个动作。

    当一个动作被调度时,你的应用中可能会发生一些事情,但这种模式的工作方式是“调度程序”不知道这些。

    saga 与组件通信的唯一常见方式是通过更改 redux 状态。因此,您不必在回调中更改本地状态,而是必须等待 dateSales 属性更改,然后使用 getDerivedStateFromProps 更新本地状态。

    static getDerivedStateFromProps(props) {
      return {salesData: props.dataSales}
    }
    

    有关使用 getDerivedStateFromProps 的更多信息,请参阅

    https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

    https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#fetching-external-data-when-props-change

    https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#when-to-use-derived-state

    https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops

    【讨论】:

      【解决方案2】:
       recievedChangeValue=(selectVal)=>{
      this.setState({selectedSalesData:selectVal},
        ()=>{
          if(selectVal==='Yearly'){
              this.props.getYearlySales() 
          }
          if(selectVal==='Decade'){ 
              this.props.getSales()
          }
        }
      )
      

      }

      以下我在render中写的

         let SalesData=this.handleSalesData(selectedSalesData)//calls on selecteddata and it works like a charm
      

      【讨论】:

        猜你喜欢
        • 2018-11-17
        • 2019-08-20
        • 2020-01-16
        • 2021-09-20
        • 2015-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多