这真的让我很有趣:
有没有一种方法可以使构造函数中的状态更美观:
state = {
team1: 0, team2: 0, team3: 0, team4: 0
}
所有值都是相同的,有没有办法缩短它并使它更美观?
谢谢!
答案 0 :(得分:0)
您可以创建一个对象并创建一个for循环,以便在每次迭代中向该对象添加一个值为'team' + index
的键0
:
class MyComponent extends React.Component {
constructor(props) {
super(props);
const state = {};
for(let i = 1; i < 5; i++) {
state['team' + i] = 0;
}
this.state = state;
}
// ...
}