状态更改时,Reach child 不会更新

Reach child does not update when state changes

我创建了一个代码片段来演示这个问题:

https://codesandbox.io/s/o1v4qxw3yy

本质上,单击复选框时,checkedValues(一个 id 数组)不会传递给 ChildComponent。除非我一起发送另一个变量。如果您在 ParentComponent 中取消对 cat 行 @32 的注释,它就会开始工作。

我注意到 ChildComponent 周围的 Apollo HOC 接收到新值 live,但是除非进行另一个状态更改,否则 ChildComponent 不会更新。

我不确定我做错了什么。

你正在改变状态。你应该保持状态不变。创建一个新数组,然后对该数组进行更改。所以转换

let newArray = this.state.checkedValues;

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

需要在Parent Component的handleChecked()方法中的setState()方法中传入一个新的数组,如下所示(可以使用展开运算符。)

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