我想把this.state.currentPlayer分配给this.state.whosPlaying。它抛出错误TypeError: Cannot read property 'currentPlayer' of undefined at new Board。
constructor(props) {
super(props);
this.state = {
symbols: [X, O],
currentPlayer: Math.floor(Math.random() * 2),
fields: Array(9).fill(null),
whosPlaying: this.state.currentPlayer,
};
}有人有这样的模式吗?
发布于 2018-05-18 13:13:23
如果使用对象字面语法,则不能在初始化期间引用对象。
如果希望根据对象中的现有属性在状态上设置属性,则可以在componentWillMount()生命周期方法中这样做。
守则如下:
内部构造函数()
constructor(props) {
super(props);
this.state = {
symbols: [X, O],
currentPlayer: Math.floor(Math.random() * 2),
fields: Array(9).fill(null)
};
}Inside ()
this.setState((prevState) => { whosPlaying: prevState.currentPlayer });注意:如果您使用的是React 16.3+,您可以考虑使用getDerivedStateFromProps()。
发布于 2018-05-18 13:06:49
我真的不认为react的状态应该是这样使用的。如果您想这样做,我只需要在设置状态之前声明currentPlayer。关于一个例子,见下文:
constructor(props) {
super(props);
const currentPlayer = Math.floor(Math.random() * 2)
this.state = {
symbols: [X, O],
currentPlayer,
fields: Array(9).fill(null),
whosPlaying: currentPlayer,
};
}https://stackoverflow.com/questions/50411952
复制相似问题