I\'m sending values of numbers from Numbers component to Main component. Everything is working fine until I set that value in my Main component to that component\'s state.<
Probably because the console.log is triggered before the new state has been really set.
You should use the function:
componentDidUpdate: function() {
console.log(this.state.number);
}
This function is triggered each time the state is updated.
Hope it helps
In order to print state number in console use
this.setState({
number: num
},function(){console.log("but wrong here (previous number): " + this.state.number)})
instead of
this.setState({
number: num
})
console.log("but wrong here (previous number): " + this.state.number)
In short: use setState(function|object nextState[, function callback])
From the docs:
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
If you want to print the change after a call to setState
, use the optional callback parameter:
this.setState({
number: num
}, function () {
console.log(this.state.number);
});
The setState method is asynchronous, so the new state is not there yet on console.log call. You can pass a callback as a second parameter to setState and call console.log there. In this case the value will be correct.
In the docs of the setState
function is an interesting note:
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.
https://facebook.github.io/react/docs/component-api.html