Reach child does not update when state changes

佐手、 提交于 2019-12-24 07:51:54

问题


I have created a code snippet to demonstrate the issue:

https://codesandbox.io/s/o1v4qxw3yy

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.

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.


回答1:


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;

to

let newArray = [...this.state.checkedValues]; 



回答2:


You need to pass a new array in setState() method in handleChecked() method of Parent Component as shown below (you can use spread operator.)

handleChecked = (e, id) => {
  console.log(id)
  let newArray = this.state.checkedValues;

  const i = newArray.indexOf(id);
  if (i === -1) newArray.push(id);
  else newArray.splice(i, 1);

  this.setState({ checkedValues: [...newArray] });
  this.setState({ cat: !this.state.cat })
  console.log(`State changed to ${this.state.checkedValues}`);
};


来源:https://stackoverflow.com/questions/47517705/reach-child-does-not-update-when-state-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!