问题描述
我创建了一个代码片段来演示问题:
https://codesandbox.io/s/o1v4qxw3yy
基本上 checkedvalues (ids数组)不会在单击复选框时传递给子组装.除非我和它一起发送另一个变量.如果在Parencomponent中取消注释Cat Line @ 32,则它一切都开始工作.
我已经注意到子组件周围的apollo hoc收到新值 live ,但除非进行另一个状态更改,否则子组件不会更新.
我不确定我做错了什么.
推荐答案
您正在突变状态.你应该保持国家的局势.创建一个新数组,然后对该数组进行更改.所以转换
let newArray = this.state.checkedValues;
let newArray = [...this.state.checkedValues];
其他推荐答案
您需要在父组件的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}`); };
问题描述
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.
推荐答案
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];
其他推荐答案
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}`); };