Reach child does not update when state changes

2019-08-10 09:20发布

问题:

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}`);
};