【问题标题】:ReactJS state change is inconsistentReactJS 状态变化不一致
【发布时间】: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


【解决方案1】:

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

其次,设置后不要使用console.log查看state的值,因为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)
    ),
}

【讨论】:

  • 你是对的,这解决了控制台日志问题。但是现在状态并没有正确地传递给所有组件。我刚刚添加了另一个组件,而 button 获得了 drawMode 的更新状态,而之前定义的另一个组件并没有同时获得它。我必须切换它两次,直到它被填充到另一个组件中。我将相应地编辑问题。
  • 能否添加“另一个”组件的代码,我去看看。
  • 也许我应该用它创建另一个问题,因为这改变了问题太多......
猜你喜欢
  • 2017-04-23
  • 2014-11-06
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 2018-11-06
  • 2017-03-24
  • 1970-01-01
相关资源
最近更新 更多