简体   繁体   English

反应-在子级上使用更新状态时,父级组件状态为什么会更改?

[英]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. this.state stateToSet[active] = false ,将引用父组件this.state ,所以我Object.assign状态和我要修改的每个属性,然后在不修改Parent状态的情况下工作。

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. 是的,所以您永远不要像在这里那样直接修改状态,因为this.setState实际上会触发组件的所有生命周期方法,而像在这里那样修改状态不会。 That function takes keys you'd like to modify so no need to Object.assign or ... . 该函数采用您想要修改的键,因此无需Object.assign...

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. 我不确定您的意思是“父母/孩子”,以及为什么要设置孩子的父母与父母的孩子有什么关系,但是如果您的意思是当孩子的状态发生变化时不重新渲染父母,那就是预期的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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