首页 > 解决方案 > setState 没有切换值并返回未定义的 React

问题描述

这可能是一个重复的问题,但我仍然无法弄清楚为什么 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>

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

标签: reactjs

解决方案


 this.setState((prevState) => ({
        isPlaying: !prevState.isPlaying
    }), function() {
   console.log("updating state....state is="+this.state.isPlaying) 
  });

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


推荐阅读