Javascript ReactJS状态更改不一致

Javascript ReactJS状态更改不一致,javascript,reactjs,Javascript,Reactjs,当我有一个名为“DrawButton”的button类时,它有这个渲染 render() { return( <Button onClick={this.props.toggleDraw.bind(this)} style={{ backgroundColor: this.props.drawMode ? 'red' : 'blue' }} >

当我有一个名为“DrawButton”的button类时,它有这个渲染

render() {
    return(
        <Button
            onClick={this.props.toggleDraw.bind(this)}
            style={{
                backgroundColor: this.props.drawMode ? 'red' : 'blue'
            }}
        >
            Draw
        </Button>
    );
}
还有一个处理函数

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>
  );
}
在setState运行之前,drawMode在setState运行之后为false,drawMode仍然为false

但是按钮仍然有一个红色的背景

再次单击按钮:

App.js drawMode:true
App.js:22
App.js drawMode:true
App.js:26
但按钮是蓝色的,在状态设置为true时,再次轻视drawMode


为什么会出现这种不一致性?

首先,您的
绑定使用不正确,在
DrawButton
onClick处理程序中,只需调用
this.props.toggleDraw
。 此代码:
This.props.toggleDraw.bind(This)
应该位于
App.js
文件的构造函数中

其次,不要使用
控制台.log
检查设置后的状态值,因为
setState
函数异步运行,请使用
setState
回调检查设置后的值:

toggleDraw = (e) => {
    console.log('App.js drawMode:' + this.state.drawMode);
    this.setState(
        { drawMode: !this.state.drawMode },
        () => console.log('App.js drawMode:' + this.state.drawMode)
    ),
}

setState
是异步的,所以在您登录时,它不会在下一行代码中更改。您的
。绑定(此)
的位置不正确,它需要位于父级而不是子级。我如何修复它保持一致?@WisnuAdiNurcahyo什么?这里没有异步函数。@bxyify那么您没有向我们显示所有代码。使用你的代码和我的修复程序,它可以正常工作(除了其他人谈论的控制台日志),你是对的,这修复了控制台日志问题。但是现在,状态不能正确地传递给所有组件。我刚刚添加了另一个组件,当button获取drawMode的更新状态时,之前定义的另一个组件不能同时获取它。我必须切换它两次,直到它填充到另一个组件。我会相应地编辑这个问题。你能添加“另一个”组件的代码吗,我会看一下。也许我应该用它创建另一个问题,因为这会改变问题太多。。。
App.js drawMode:true
App.js:22
App.js drawMode:true
App.js:26
toggleDraw = (e) => {
    console.log('App.js drawMode:' + this.state.drawMode);
    this.setState(
        { drawMode: !this.state.drawMode },
        () => console.log('App.js drawMode:' + this.state.drawMode)
    ),
}