简体   繁体   English

ReactJS state变化不一致

[英]ReactJS state change is inconsistent

When I have a button class called "DrawButton", that has this render当我有一个名为“DrawButton”的按钮 class 时,它具有此渲染

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在父 App.js 中定义了 state

state = {
        drawMode: false
}

and there is a handler function并且有一个处理程序 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. state 未正确更新。 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. setState 运行前,drawMode 为 false,setState 运行后,drawMode 仍为 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.但是按钮是蓝色的,再次鄙视 state 中的 drawMode 设置为 true。

Why is this inconsistency happening?为什么会出现这种不一致?

Firstly, your bind was used incorrectly, in your DrawButton onClick handler, just call this.props.toggleDraw .首先,您的bind使用不正确,在您的DrawButton onClick 处理程序中,只需调用this.props.toggleDraw This code: this.props.toggleDraw.bind(this) should be in the constructor of App.js file.这段代码: this.props.toggleDraw.bind(this)应该在App.js文件的构造函数中。

Secondly, do not use the console.log to check the value of state after setting, because the setState function runs asynchronously, use setState callback to check the value after setting:其次,设置后不要使用console.log查看state的值,因为setState function是异步运行的,使用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)
    ),
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM