reactjs - 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>
如果您发现错误,请告诉我。提前致谢。
解决方案
this.setState((prevState) => ({
isPlaying: !prevState.isPlaying
}), function() {
console.log("updating state....state is="+this.state.isPlaying)
});
Setstate 是异步的,在回调中给控制台日志。
推荐阅读
- c# - 未使用 URL 重写(出站规则)从所有网站中删除 HTTP 响应标头
- php - PHP array_multisort 未按预期使用双多维数组进行排序
- jmeter - JMeter 的 Taurus YAML 运行时属性更改
- javascript - Firestore - 如何在我的州添加文档 ID 及其数据?
- bash - 写入输出流并从 shell 脚本函数返回值
- postgresql - postgresql 函数在声明附近有语法错误?
- c# - 命令设计模式 - 执行带有返回值的方法
- windows-subsystem-for-linux - (启动时出现 WSL 错误)按任意键继续
- c# - 如何使用 ASP.NET 样板实现多个通知程序?
- git - go-git 将文件报告为 Untracked 而它应该是 Unmodified