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.
var Numbers = React.createClass({
handleClick: function(number){
this.props.num(number)
},
render: function(){
return (
<div>
<button onClick={this.handleClick.bind(null, 1)}>1</button>
<button onClick={this.handleClick.bind(null, 2)}>2</button>
<button onClick={this.handleClick.bind(null, 3)}>3</button>
</div>
)
}
})
var Main = React.createClass({
getInitialState: function(){
return {
number: 0
}
},
handleCallback: function(num){
console.log("number is right here: " + num);
this.setState({
number: num
})
console.log("but wrong here (previous number): " + this.state.number)
},
render: function() {
return (
<Numbers num={this.handleCallback} />
//<SomeComponent number={this.state.number} />
)
}
});
React.render(<Main />, document.getElementById('container'));
Why is it behaving like this? Second console.log
in handleCallback
function prints the previous number, not the number which is in num
parameter. I need right number to be in my state, because I'm going to send it immediately as an props in my SomeComponent
component.
https://jsfiddle.net/69z2wepo/13000/
Sending state/props to another component using the onClick event: So first we store the state/props into the parent component i.e in which component where we trigger the onClick event. Then to pass the state into another component, we simply pass it as a prop.
To update our state, we use this. setState() and pass in an object. This object will get merged with the current state. When the state has been updated, our component re-renders automatically.
So, when you mutate the state directly and call setState() with an empty object. The previous state will be polluted with your mutation. Due to which, the shallow compare and merge of two states will be disturbed or won't happen, because you'll have only one state now.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With