Reputation: 561
I have the following code in which I get the current state of year
, which changes when you press a button in the main component:
componentWillReceiveProps(nextProps){
this.setState({
update: true
});
if(nextProps.year===2019){
console.log('oneeeeeee',this.state.update)
this.setState({
dates: ['09.2018', '10.2018', '11.2018', '12.2018'],
numbers: ['3000', '4000', '3300', '2700'],
},() => {
this.setState({update: false})
});
}
}
The problem is that I work with a schedule that catches every button click in the menu itself, and re-draws the schedule when I click it.
If I remove the update
property, everything works fine. Each time, when changing the year
, I assign an update
to true
, and transfer to it new data. After that, I want to transfer to the update: false
Tell me, please, how can I transfer false
to update
, only after I transferred the data to dates
and numbers
?
I tried to use callback, but it does not work. Thanks for any of your tips!
Upvotes: 0
Views: 93
Reputation: 282160
There are a few things that you need to correct.
First: First, setState is async and batched and hence calling setState for update: true
and would update the state immediately
Second: You must always compare current and nextProps in before executing anything in componentWillReceiveProps
Third: componentWillReceiveProps
is deprecated since v16.3.0 and hence I recomment you use componentDidUpdate
instead
Example using componentWillReceiveProps
componentWillReceiveProps(nextProps){
if (nextProps.year !== this.props.year && nextProps.year === 2019) {
this.setState({
update: true
}, () => {
this.setState({
dates: ['09.2018', '10.2018', '11.2018', '12.2018'],
numbers: ['3000', '4000', '3300', '2700'],
},() => {
this.setState({update: false})
});
})
}
}
Upvotes: 3