【发布时间】:2017-03-08 04:15:01
【问题描述】:
您好,情况是这样的。我正在用 react 构建一个 tictactoe 游戏,我有 3 个组件 1. 游戏家长 2. 董事会 3. 游戏控制
我在 GameParent 组件中有一个函数,它有两个状态属性,称为 AI 和 Game,它们是对象。我将这些对象作为道具传递给板组件。它还有一个叫做 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() 被调用时,Game 对象内部有一个名为 status 的属性,应将其更改为“正在运行”
我将 startGame() 函数传递给我的 gameControls 组件,并将它附加到我的开始按钮 onClick 处理程序。
我的棋盘组件处理棋盘方块上的点击,但它仅在 Game.status ===“正在运行”时注册点击,但我不断获取状态 ===“开始”的对象。
所以当我添加这 4 个 console.logs 时,当我只打印出这个时,我看到 Game 对象的状态是“开始”但是当我 console.log this.state 和 this.state.Game 时,状态是设置为“运行”!
我很困惑为什么会发生这种情况......我猜这是 React 更新它的孩子的方式,但我还没有通过阅读 render() 和 setState() 的工作原理找到解释。或者当我将函数和对象传递给子组件时,我可能没有完全理解“this”的影响。
如果你们想看完整的代码,这里是链接 http://codepen.io/comc49/pen/WRqBXr?editors=0110
【问题讨论】:
-
这可能与stackoverflow.com/q/23392111/218196 存在相同的问题。
标签: javascript reactjs this reactive-programming