[英]Accessing a state object in the this.state constructor
I have a state with 2 objects (players), of which only 1 can be the player on turn. 我有一个包含2个对象(玩家)的状态,其中只有1个对象可以依次进入。
How do I save the player on turn into the state, so I can use its data? 如何将播放器保存到转入状态,以便可以使用其数据?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
playerOne: {
name: "foo"
},
playerTwo: {
name: "bar"
}
playerOnTurn: {} // This has to become the same Object as 'playerOne'.
}
}
}
I have tried the following 3 things: 我已经尝试了以下3件事:
playerOnTurn: this.state.playerOne
Unfortunately it doesn't work , as the state isn't yet defined due to still constructing the state. 不幸的是, 它不起作用 ,因为由于仍在构造状态,因此尚未定义状态。
2) Writing the same Object twice: 2)两次写入同一对象:
playerOnTurn: { name: "foo" }
It works , but I don't want to write it twice, because a player can contain many properties. 它可以工作 ,但是我不想写两次,因为一个播放器可以包含许多属性。 It seems like a bad solution in terms maintainability.
就可维护性而言,这似乎是一个糟糕的解决方案。 Because properties could be added/removed later, which could cause them to become nonidentical.
因为可以稍后添加/删除属性,这可能导致它们变得不相同。
3) Declaring the object before setting it in the state: 3)在将对象设置为状态之前对其进行声明:
class App extends React.Component { constructor(props) { super(props); const playerOne = { name: "foo" } this.state = { playerOne: playerOne, playerTwo: { name: "bar" } playerOnTurn: playerOne } } }
It works , but it doesn't seem like a great solution in terms of readability. 它可以工作 ,但是就可读性而言,似乎不是一个很好的解决方案。 Because I declare both players in different ways.
因为我以不同的方式宣布两个球员。
Maybe it requires a different approach? 也许需要不同的方法? Eg by adding a boolean
onTurn
to each player? 例如,通过向每个玩家添加布尔值
onTurn
?
Any input/advice is welcome. 欢迎任何意见/建议。
Your 3rd option is correct, if you want it to not look like you are declaring them in different ways, you can do, 您的第三个选项是正确的,如果您不希望它看起来像您以不同的方式声明它们,则可以这样做,
const playerOne = {
name: "foo"
}
const playerTwo = {
name: "bar"
}
this.state = {
playerOne,
playerTwo,
playerOnTurn: playerOne
}
In this case, you should use componentDidMount lifecycle method to update your state. 在这种情况下,您应该使用componentDidMount生命周期方法来更新状态。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
playerOne: {
name: "foo"
},,
playerTwo: {
name: "bar"
}
playerOnTurn: {}
}
}
setPlayerOnTurn(player){
this.setState({ playerOnTurn : player });
}
componentDidMount(){
// other initialization
this.setPlayerOnTurn(this.state.playerOne);
}
}
You can use a getter function, which allows you to access this
(in context of the object) inside a function: 您可以使用getter函数,该函数允许您在函数内部访问
this
函数(在对象的上下文中):
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
playerOne: {
name: "foo"
},,
playerTwo: {
name: "bar"
}
get playerOnTurn() {
return this.playerOne
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.