【发布时间】:2019-10-28 01:33:31
【问题描述】:
当我有一个名为“DrawButton”的按钮类时,它具有此渲染
render() {
return(
<Button
onClick={this.props.toggleDraw.bind(this)}
style={{
backgroundColor: this.props.drawMode ? 'red' : 'blue'
}}
>
Draw
</Button>
);
}
在父 App.js 中定义状态
state = {
drawMode: false
}
还有一个处理函数
toggleDraw = (e) => {
console.log('App.js drawMode:' + this.state.drawMode);
this.setState({
drawMode: !this.state.drawMode
});
console.log('App.js drawMode:' + this.state.drawMode);
}
最后是按钮:
render() {
return (
<div className="App">
<DrawButton
toggleDraw={this.toggleDraw}
drawMode={this.state.drawMode}
/>
</div>
);
}
状态未正确更新。 它输出以下内容:
首先点击按钮
App.js drawMode:false
App.js:27
App.js drawMode:false
App.js:31
setState 运行前,drawMode 为 false,setState 运行后,drawMode 仍为 false。
但按钮仍然是红色背景。
第二次点击按钮:
App.js drawMode:true
App.js:22
App.js drawMode:true
App.js:26
但是按钮又是蓝色的,鄙视drawMode的状态设置为true。
为什么会出现这种不一致?
【问题讨论】:
-
setState是异步的,所以在你记录的时候不会在下一行代码改变 -
你的
.bind(this)放错地方了,它需要在父母而不是孩子。 -
如何解决它保持一致的问题?
-
@WisnuAdiNurcahyo 什么?这里没有异步功能。
-
@bxyify 那么您并没有向我们展示所有代码。使用您的代码和我的修复它可以正常工作(禁止其他人谈论的控制台日志)jsfiddle.net/dh7mkzwq
标签: javascript reactjs