0
votes

I have a parent class component that has a function in componentWillMount that loops through a list of strings and creates an element for each one and finally setState on this.state.map. Each child element receives a prop which is a state in parent called this.state[element].

The reason I put these elements into this.state.map was because I can change things in (some) upper components without having to re-render the array each time (which is painfully slow) and I didn't want to use shouldComponentUpdate. Plus in the future I can just quickly change elements by toggling different map states.

The problem is, when the parent this.state[element] (that's passed to child as props in the initial componentWillMount) changes, it doesn't update the props for the child. Parent state does change though.

Is this a legit way to do this? I'm sorry I didn't provide code sample. It's just such a mess at the moment.

1

1 Answers

0
votes

Only ReactDOM.render (and serverside rendering etc.), setState, or forceUpdate, will cause your children to re-render. If you are just mutating the state object, React is unaware of this, and will not re-render. Anyways, mutating the state not through setState is not valid, and you should try to keep your state as immutable as possible. In order for you to see the changes in your children, you need to use setState to update this.state[element].

From the React docs:

Notes: NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.