我有一个带有2个对象(玩家)的状态,其中只有1个对象可以依次进入。
如何保存播放器转入状态,以便可以使用其数据?
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'.
}
}
}
我尝试了以下3件事:
playerOnTurn: this.state.playerOne
不幸的是,由于仍在构造状态,因此尚未定义状态,因此它不起作用。
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:
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? E.g. by adding a boolean onTurn
to each player?
Any input/advice is welcome.
You can use a getter function, which allows you to access this
(in context of the object) inside a function:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
playerOne: {
name: "foo"
},,
playerTwo: {
name: "bar"
}
get playerOnTurn() {
return this.playerOne
}
}
}
}
@UniqIdentifierAssignedAtBirth有吗?
this
在这种情况下,对象是对象,而不是类。它确实起作用,在这种情况下,它
this
指向对象:this.state
谢谢您的回答,这正是我所需要的。:)无论如何,您无法在需要时将播放器设置为打开状态,因此不切实际。更重要的是,您不能将getter和setter放入react状态对象中。stackoverflow.com/questions/50387670/…当您设置状态时,它们将被擦除
您不能在反应状态下使用setter和getter。你必须使用
setState
和纯粹的对象确实,将吸气剂放入状态对象的意义何在?