状态更改时,到达儿童不会更新 [英] Reach child does not update when state changes
问题描述
我创建了一个代码片段来演示该问题:
I have created a code snippet to demonstrate the issue:
https://codesandbox.io/s/o1v4qxw3yy
基本上,单击复选框时, checkedValues (id的数组)不会传递给ChildComponent.除非我与它一起发送另一个变量.如果您取消注释ParentComponent中的cat行@ 32,则所有这些都将开始工作.
Essentially the checkedValues (an array of ids) does not get passed to the ChildComponent when a checkbox is clicked. Unless I send another variable along with it. If you uncomment the cat line @32 in the ParentComponent, it all starts working.
我注意到ChildComponent周围的Apollo HOC收到了新值 live ,但是ChildComponent不会更新,除非进行了其他状态更改.
I have noticed that the Apollo HOC around the ChildComponent receives the new value live, but the ChildComponent does not update unless another state change is made.
我不确定自己在做什么错.
I am not sure what I am doing wrong.
推荐答案
您正在改变状态.您应该保持状态不变.创建一个新的数组,然后对该数组进行更改.所以转换
You are mutating the state. You should keep the state immutate. Create a new array and then make the changes to that array. So convert
let newArray = this.state.checkedValues;
到
let newArray = [...this.state.checkedValues];
这篇关于状态更改时,到达儿童不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!