温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Accessing a state object in the this.state constructor

javascript - 在this.state构造函数中访问状态对象

发布于 2020-03-27 11:21:55

我有一个带有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件事:


1)直接访问状态(在状态内):
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.

查看更多

查看更多

提问者
Daan
被浏览
16
Kobe 2019-07-03 22:29

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
      }
    }
  }
}

发布
问题

分享
好友

手机
浏览

扫码手机浏览