简体   繁体   中英

react - Why does Parent Component state change when using updating state on Child?

When I modify state on child components by doing something like this:

// inside child component
var stateToSet = this.state;
stateToSet[active] = false;
this.setState(nextState);

Parent State changes without rerendering.

I suppose the Parent Component this.state is being referenced when stateToSet[active] = false , so I Object.assign 'd the state and each property I want to modify, and then it works without modifying Parent's state.

I would like to now why is this happening. Could this be intended behavior? Could Brunch(my compiler) and concatenating files be the problem?

Any ideas?

Yup so you should never modify the state directly like you're doing here because this.setState will actually trigger all the lifecycle methods of your component and modifying state like here will not. That function takes keys you'd like to modify so no need to Object.assign or ... .

this.setState({ active: false })

I'm not sure what you mean by Parent/child though and why setting the child's parent would have anything to do with the parent's, but if you mean that the parent is not re-rendered when the child's state changes, then that is the intended behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM