When I have a button class called "DrawButton", that has this render
render() {
return(
<Button
onClick={this.props.toggleDraw.bind(this)}
style={{
backgroundColor: this.props.drawMode ? 'red' : 'blue'
}}
>
Draw
</Button>
);
}
And in parent App.js the state gets defined
state = {
drawMode: false
}
and there is a handler function
toggleDraw = (e) => {
console.log('App.js drawMode:' + this.state.drawMode);
this.setState({
drawMode: !this.state.drawMode
});
console.log('App.js drawMode:' + this.state.drawMode);
}
And finally the button:
render() {
return (
<div className="App">
<DrawButton
toggleDraw={this.toggleDraw}
drawMode={this.state.drawMode}
/>
</div>
);
}
The state doesn't get updated properly. It outputs the following:
First click on the Button
App.js drawMode:false
App.js:27
App.js drawMode:false
App.js:31
Before the setState ran, the drawMode is false after setState ran, the drawMode is still false.
But the button still gets a red background.
Second click on the Button:
App.js drawMode:true
App.js:22
App.js drawMode:true
App.js:26
But the button is blue again despise drawMode in state is set to true.
Why is this inconsistency happening?