Warm tip: This article is reproduced from stackoverflow.com, please click
javascript reactjs

Accessing a state object in the this.state constructor

发布于 2020-03-27 10:24:19

I have a state with 2 objects (players), of which only 1 can be the player on turn.

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:


1) Directly accessing the state (within the state):
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:

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.

Questioner
Daan
Viewed
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
      }
    }
  }
}