【问题标题】:setState is not toggling values and returning undefined ReactsetState 没有切换值并返回未定义的 React
【发布时间】:2020-05-17 00:06:02
【问题描述】:

这可能是一个重复的问题,但我仍然无法弄清楚为什么 setState 无法切换布尔值?以下是函数:

constructor(props){
    super(props)
    this.state = {
        isPlaying: false
    }
}

playButtonClicked = () => {
    this.setState((prevState) => ({
        isPlaying: !prevState.isPlaying
    }))
    console.log("updating state....state is="+this.isPlaying)  // Its printing undefined
    this.togglePlayPause();
}

这是 div:

<button id="play-pause" onClick={this.playButtonClicked}></button>

如果您发现错误,请告诉我。提前致谢。

【问题讨论】:

  • this.state.isPlaying 应该进入 console.log。此外,控制台日志可能不会显示您的最新状态。所以,使用 setstate 的回调。
  • 首先,您尝试登录的 this.isPlaying 无效。会 this.state.isPlaying,setState 也是异步的,当你尝试记录它时它不会被更新。
  • 这能回答你的问题吗? React setState not updating state

标签: reactjs


【解决方案1】:
 this.setState((prevState) => ({
        isPlaying: !prevState.isPlaying
    }), function() {
   console.log("updating state....state is="+this.state.isPlaying) 
  });

Setstate 是异步的,在回调中给控制台日志。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多