How Do I Update The State (using Reactjs) If I Should Not Call Setstate In Componentwillupdate?
Solution 1:
First thing to do is to check official documentation for this method (link). Where you can read when the function is actually called.
Then read common mistake(note):
You cannot use this.setState() in this method. If you need to update state in response to a prop change, use componentWillReceiveProps instead.
You change the state and React automatically calls componentWillUpdate
.
Solution 2:
I understand this is cautioned against in the guide but I am not sure I can see the problem with calling setState
from within componentWillUpdate
. True, it may result in infinite recursion unless of course you provide a bottom to that recursion (a way to break out of it). E.g. a way could be to check the second (nextState
) parameter in componentWillUpdate
and not invoke setState
again if some condition is met (which is when the recursion ends).
As a minimal example, imagine a component that has no properties at all, only two pieces of state. Further imagine that the second piece of state is asynchronously obtained from the first. E.g. the first piece of state could be some parameter to provide to an Ajax call, and the second piece of state is the result of that call. So basically you call this.setState
to configure the parameters and then inside componentWillUpdate
you can do something like the following (to keep things simple I use a window.setTimeout
as a placeholder for an Ajax call):
constComponentWithAsyncState = React.createClass({
getInitialState: function() {
return {
ajaxParams: '',
ajaxResult: ''
};
},
setAjaxParams: function(params) {
this.setState({ajaxParams: params});
},
componentWillUpdate: function(_, nextState) {
if (nextState.ajaxParams!=this.state.ajaxParams)
window.setTimeout(functionimagineThisIsAjax() {
this.setState({ajaxResult: `result from ${nextState.ajaxParams}`});
}.bind(this), 2000);
},
When, (e.g. through some controls managed by this component) the ajaxParams
change, the sequence of actions will be something like (where ~~>
denotes asynchronicity):
setAjaxParams --> this.setState --> componentWillUpdate ~~> imagineThisIsAjax --> this.setState --> componentWillUpdate
I.e. the second call to componentWillUpdate
will not result in a further this.setState
and thus the recursion will end there.
Post a Comment for "How Do I Update The State (using Reactjs) If I Should Not Call Setstate In Componentwillupdate?"