How to call a function before and then depending on data update state-React-redux

谁说胖子不能爱 提交于 2019-12-11 16:42:49

问题


I've a drop down on select the saga is called and the same component must be used. The sagas are called the only thing not happening is the set state is updating before the saga call therefore the component never updates the data.

            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**                                           
                }
            }

I know the callback but here the state must be updated only after the saga call.I'm working onto it since past day I've no idea as to what has to be done. Any help is appreciated.Please lemme know as to where i'm going wrong.


回答1:


You can't wait in component for the saga to finish, because this.props.getSales isn't really calling a saga - it is just dispatching an action.

When an action is dispatched something can happen in your app based on that, but the way the pattern works is that the "dispatcher" doesn't know about any of that.

The only common way saga can communicate with components is through changing redux state. So instead of changing local state in the callback you will have to wait for the dateSales prop to change and then update the local state using getDerivedStateFromProps.

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

For more info on using getDerivedStateFromProps see

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()
    }
  }
)

}

The following I wrote in render

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


来源:https://stackoverflow.com/questions/55664378/how-to-call-a-function-before-and-then-depending-on-data-update-state-react-redu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!