gpt4 book ai didi

javascript - 将数组的元素作为 React 中对象的一部分推送

转载 作者:行者123 更新时间:2023-11-29 22:56:02 25 4
gpt4 key购买 nike

我有这门课:

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 文章中所述),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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com