[英]How can I use this.state within this.state
I want to assign this.state.currentPlayer
to this.state.whosPlaying
. 我想将this.state.currentPlayer
分配给this.state.whosPlaying
。 It throws the error TypeError: Cannot read property 'currentPlayer' of undefined at new Board
. 它引发错误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,
};
}
Has someone a pattern for this? 有人为此有模式吗?
You cannot reference an object during initialization if you are using the object literal syntax. 如果使用对象文字语法,则无法在初始化期间引用对象。
If you want to set a property on state based on an existing property in the object, you can do so in the componentWillMount()
lifecycle method. 如果要基于对象中的现有属性在状态上设置属性,则可以在componentWillMount()
生命周期方法中进行设置。
The code would look as follows: 该代码如下所示:
Inside constructor() 内部构造函数()
constructor(props) {
super(props);
this.state = {
symbols: [X, O],
currentPlayer: Math.floor(Math.random() * 2),
fields: Array(9).fill(null)
};
}
Inside componentWillMount() 内部componentWillMount()
this.setState((prevState) => { whosPlaying: prevState.currentPlayer });
Note: If you are using React 16.3+, you could consider using getDerivedStateFromProps(). 注意:如果您使用的是React 16.3+,则可以考虑使用getDerivedStateFromProps()。
Just use an intermediate variable: 只需使用一个中间变量:
constructor(props) {
super(props);
const currentPlayer = Math.floor(Math.random() * 2);
this.state = {
symbols: [X, O],
currentPlayer,
fields: Array(9).fill(null),
whosPlaying: currentPlayer,
};
}
Or just set it after the object literals end: 或者只是在对象常量结束后进行设置:
this.state = { currentPlayer: Math.floor(Math.random() * 2) };
this.state.whosPlaying = this.state.currentPlayer;
I don't really think react's state is supposed to be used like this. 我真的不认为应该这样使用react的状态。 If you would like to do this I would just declare the currentPlayer before you set the state. 如果您想这样做,我将在设置状态之前声明currentPlayer。 See below for an example: 参见以下示例:
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.