[英]How can I use this.state within this.state
我想将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,
};
}
有人为此有模式吗?
如果使用对象文字语法,则无法在初始化期间引用对象。
如果要基于对象中的现有属性在状态上设置属性,则可以在componentWillMount()
生命周期方法中进行设置。
该代码如下所示:
内部构造函数()
constructor(props) {
super(props);
this.state = {
symbols: [X, O],
currentPlayer: Math.floor(Math.random() * 2),
fields: Array(9).fill(null)
};
}
内部componentWillMount()
this.setState((prevState) => { whosPlaying: prevState.currentPlayer });
注意:如果您使用的是React 16.3+,则可以考虑使用getDerivedStateFromProps()。
只需使用一个中间变量:
constructor(props) {
super(props);
const currentPlayer = Math.floor(Math.random() * 2);
this.state = {
symbols: [X, O],
currentPlayer,
fields: Array(9).fill(null),
whosPlaying: currentPlayer,
};
}
或者只是在对象常量结束后进行设置:
this.state = { currentPlayer: Math.floor(Math.random() * 2) };
this.state.whosPlaying = this.state.currentPlayer;
我真的不认为应该这样使用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,
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.