Reputation: 1250
One of my React component receive a Array of JSON. And the component contain a componentDidUpdate. I know this function run right before rendering, and I get to see the nextProps and nextState, so I can compare them with the current. However the inner working confuses me
Here are the steps of my program:
This component run componentDidUpdate:
differenceList
) this component render according to the differenceList
Following is my console.log that I've placed all over.
//after I trigger a update of the list
self.setState({differenceList: self.state.differenceList.concat(item.id)});
why is #4
showing empty??
at #6
why did it enter componentWillUpdate again? is it because I updated the state inside componentWillUpdate? but if so why is #5
showing empty state #8
Now after entering render function again, it suddenly show the changed state
Upvotes: 1
Views: 242
Reputation: 5569
The answer is because setState
is asynchronous.
<Parent/>
tries to render <Child list={[1, 2, 1336]}/>
(Batch 0)
willUpdate()
gets called with nextProps = {list: [1, 2, 1336]}
self.setState({differenceList: self.state.differenceList.concat(['1336'])}) // This code is asynchronous, creating Batch 1
willUpdate()
, this.state is still the samerender()
setState()
call)
willUpdate()
with nextState = { ... differenceList: ['1336'] }
this.state
still not updatedwillUpdate()
render()
with new stateI'm not sure I'm being very clear, I'm a bit tired.
Anyways, you should not be using this.setState
in componentWillUpdate()
.
Try using componentWillReceiveProps()
for your purposes.
Upvotes: 2