【发布时间】:2019-03-21 03:28:29
【问题描述】:
我目前正在构建一个井字游戏,并希望将当前玩家的状态存储为 currentPlayer。在一个玩家移动后,我将 currentPlayer 更新为对面的玩家。但是,当我尝试将新状态记录到控制台时,它不会产生更新状态的值。
这是我的代码:
state = {
currentPlayer: 'X',
}
// This function is triggered by an onClick attribute.
// It first finds the html element and renders the currentPlayer value from state.
// It then switchs the value of currentPlayer from X to O and calls setState to update the state.
// Why does the console.log not show the updated state value?
userDidMove = () => {
document.getElementById('cell').innerHTML = this.state.currentPlayer
let nextPlayer = this.state.currentPlayer === 'X' ? 'O' : 'X'
this.setState({
currentPlayer: nextPlayer,
})
console.log ('userDidMove changed state with ',this.state.currentPlayer)
}
任何帮助弄清楚如何让这个函数返回更新的状态值会很棒!
【问题讨论】:
-
向我们展示 this.setState()
-
@user5328504 在第 13 行。
-
setState() 是一个函数....该函数是在您提供的代码中定义的
-
我明白了...没有阅读反应标签...删除了我的答案!
-
@user5328504 np,伙计。感谢您的努力!
标签: javascript reactjs tic-tac-toe setstate