将信息存储为静态函数与静态对象之间的差异

时间:2018-01-19 02:00:57

标签: javascript reactjs ecmascript-6

我不确定我是否正确地表达了这个问题,但实质上我正在遵循一个教程,我们需要一种方法将反应类组件的状态重置为初始状态。我继续通过创建具有初始值的对象并将组件状态设置为等于它来实现它:

// My implementation *****************************************
class Game extends React.Component {
  // store the initial state of the game
  static initialState = {
    selectedNumbers: [],
    numberOfStars: Game.randomNumber(),
    answerIsCorrect: null,
    usedNumbers: [],
    allowedRedraws: 5,
    doneStatus: ''
  }

  // set the React state to the initial state
  state = Game.initialState;

  // Reset the game.
  resetGame = () => {
    this.setState(Game.initialState);
  }
}
// ************************************************************

但是当我继续观看视频时,导师通过制作一个返回对象的静态函数来实现它:

// Tutorial implementation ************************************`
class Game extends React.Component {
  // store the initial state of the game
  static initialState = () => ({
    selectedNumbers: [],
    numberOfStars: Game.randomNumber(),
    answerIsCorrect: null,
    usedNumbers: [],
    allowedRedraws: 5,
    doneStatus: ''
  })

  // set the React state to the initial state
  state = Game.initialState();

  // Reset the game.
  resetGame = () => {
    this.setState(Game.initialState);
  }
}
// ************************************************************

所以我的问题是:这两个实现之间有什么区别可能很重要吗?或者它们基本相同?

我可能会过度思考,但我不确定JavaScript是否存在某些方面或者Reactjs处理可能使导师实施更好的状态的方式。

顺便说一句,是否有充分的理由让它们变得静止?如果它们不是更好的话会更好,这样就可以更容易地创造出不同的东西如果需要,具有不同初始状态值的实例?

1 个答案:

答案 0 :(得分:1)

你的第二个例子是不正确的。您需要调用Game.initialState,然后返回一个新对象。

resetGame = () => {
    this.setState(Game.initialState());
}

此时,不同之处在于,在示例一中,initialState可能会意外突变,并且当状态重置时,您最终会出现意外的初始状态。

在示例二中,每次调用函数创建初始状态时,它都会重新创建对象。因此,它会使意外地改变游戏的重置对象变得更加困难。

相关问题