我有这个课:

export default class Player {
  constructor() {
    this.scores = [];
  }

 // Insert a new score and keep top N
 insertScore = (score) => {
    this.scores.push(score);
    this.scores.sort((a, b) => b - a);
    if (this.scores.length > N) this.scores.pop();
  };
}


这是组件状态的一部分:

export default class Menu extends React.PureComponent {
   contructor(props){
     super(props);
     this.state = {
       player: new Player()
     }
   }

   onEndGame(score) {
     player.insertScore(score);
   }
   ...
}


由于将数组作为状态的一部分进行更改,因此在React中非常棘手(如this aritcle中所述),在这种情况下insertScore是“合法”的吗?

最佳答案

您正在直接修改状态(this.state.player.scores)的嵌套属性,因此它是不正确的。

我会尝试的:

玩家等级

insertScore = (score) => {
    this.scores.push(score);
    this.scores.sort((a, b) => b - a);
    if (this.scores.length > N) this.scores.pop();

    return this;
};


菜单类

onEndGame(score) {
    this.setState({
       player: this.state.player.insertScore(score);
    });
}

关于javascript - 在React中将数组元素作为对象的一部分推送,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56644971/

10-12 06:03