<分区>
我正在学习 React 并试图了解如何更好地处理使用数组更新组件的状态。下面是我在组件的 componentWillMount()
上调用的函数,用于生成稍后在该父组件中呈现的组件:
generateThings = () => {
let newThings = [];
for (let j = 0; j < this.state.numberOfThings; j++) {
const pos = this.generatePosition(1, 1);
const thingComp = <Thing key={j} position={pos} />;
newThings.push(thingComp);
}
this.setState({
things: newThings
});
};
我认为更好的方法是 push()
直接到状态字段 (this.state.things.push(thingComp);
) 而不是存储在一个看起来更困惑的临时变量中。但这似乎不会触发 UI 更新,所以我猜这是这样做的方法,但我不确定。