I am learning react and trying to understand how to better deal with updating state of a component with arrays. Here is the function I call on componentWillMount()
of a component to generate components that I render later in this parent component:
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
});
};
I thought a better way would be to push()
to the state field directly (this.state.things.push(thingComp);
) instead of the storing in a temp variable which seems messier. But that doesn't seem to trigger a UI update, so I'm guessing this is the way to do it, but i'm not sure.