I'm trying to use reactjs to update a state, and once it is updated fire an ajax call requesting a new page. Just before the ajax call fires an offset variable is set: var offset = this.state.npp * this.state.page;
However I find after clickNextPage() is fired, the value of this.state.page is not updated.
I fundamentally do not understand what is happening here, this appears to be a race condition, because I watch the state change on my render() function with {this.state.page}.
How can I ensure my this.state.page is updated, and then fire findByName()?
clickNextPage: function(event){
console.log("clicked happend")
page = this.state.page;
console.log(page)
page += 1
console.log(page)
this.setState({page: page});
console.log(this.state.page)
this.findByName()
},
JS Console:
clicked happend
0
1
0
setState
is asynchronous in that this.state
will not be updated right away. The short answer to your quandary is use the callback (the second parameter to setState
) which is invoked after the internal state is been updated. For example
this.setState({page: page}, function stateUpdateComplete() {
console.log(this.state.page)
this.findByName();
}.bind(this));
The longer answer is that after you call setState
, three functions are called (see here for more details about each https://facebook.github.io/react/docs/component-specs.html):
shouldComponentUpdate
this allows you to inspect the previous and new state to determine whether the component should update itself. If you return false, the following functions are not executed (although the this.state
will still be updated within your component)componentWillUpdate
this gives you a chance to run any code before the new state is set internally and rendering happensrender
this happens between the component "will" and "did" functions.componentDidUpdate
this gives you a chance to run any code after the new state is set and the component has re-rendered itselfCollected from the Internet
Please contact [email protected] to delete if infringement.
Comments