如何根据数据更新状态-React-redux之前和之后调用函数

问题描述 投票:0回答:2

我有一个下拉选择saga被调用,必须使用相同的组件。传奇被称为唯一没有发生的事情是set状态在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**                                           
                }
            }

我知道回调,但是这里状态必须在传奇之后才更新。我正在研究它,因为我不知道要做什么。任何帮助都表示赞赏。请知道我哪里出错了。

react-redux redux-saga
2个回答
0
投票

你不能在组件中等待传奇完成,因为this.props.getSales并没有真正称之为传奇 - 它只是派遣一个动作。

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

saga与组件通信的唯一常见方式是通过改变redux状态。因此,不必在回调中更改本地状态,而是必须等待dateSales prop更改,然后使用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


0
投票
 recievedChangeValue=(selectVal)=>{
this.setState({selectedSalesData:selectVal},
  ()=>{
    if(selectVal==='Yearly'){
        this.props.getYearlySales() 
    }
    if(selectVal==='Decade'){ 
        this.props.getSales()
    }
  }
)

}

以下我在渲染中写道

   let SalesData=this.handleSalesData(selectedSalesData)//calls on selecteddata and it works like a charm
© www.soinside.com 2019 - 2024. All rights reserved.