嗨,情况是这样的。我正在用react构建一个tictactoe游戏,我有3个组件1. GameParent 2.棋盘3. gameControls
我在GameParent组件中有一个函数,它有两个状态属性,分别称为AI和游戏,它们都是对象。我将这些对象作为道具传递给board组件。它还有一个名为startGame()的函数
startGame() {
let newAI = new AI(this.state.AIIdentity);
let newGame = new Game(newAI,this.state.AIIdentity);
this.state.AI.plays(this.state.Game);
this.state.Game.start();
this.setState({
start: true,
AI: newAI,
Game: newGame,
});
console.log("THIS!!!",this)
console.log("THIS!!!",this.state)
console.log("THIS!!!",this)
console.log("THIS!!!",this.state.Game);
}当调用this.state.Game.start()时,游戏对象内部有一个名为status的属性,该属性应更改为"running“
我将startGame()函数传递给gameControls组件,并将其附加到start按钮onClick处理程序。
我的面板组件处理面板方块上的点击,但它只在Game.status ===“运行”的情况下才会注册点击,但我一直在获取状态===为“===”的对象。
所以当我添加这4个console.logs时,当我只打印出来时,我看到游戏对象的状态是“开始”,但是当我console.log this.state和this.state.Game时,状态设置为"running"!
我很困惑为什么会发生这样的事情。我猜这是React更新它的子级的方式,但我还没有从render()和setState()的工作原理中找到解释。或者,当我将函数和对象传递给子组件时,我可能没有完全理解“这”是如何影响的。
如果你们想看完整的代码,这里是链接http://codepen.io/comc49/pen/WRqBXr?editors=0110
发布于 2017-03-08 15:00:41
this.setState的原因之一,这意味着不能保证在调用this.setState之后立即设置状态。这可以解释console.logs的意外输出
https://stackoverflow.com/questions/42662904
复制相似问题