如何将React setstate方法与对象数组和prevState一起使用



我在React中配置了一个状态,它是一个对象数组:

state = {
metric: [{name: "", type:"", reward: false}],
}

我希望在选中特定复选框时更新奖励属性(从false->true或true->false(,我编写了一个onSelectedChange函数,该函数使用数组中的特定索引作为参数:

onSelectedChange = (idx) => {
this.setState((prevState) => ({
metric:{
[idx]: {
...prevState.metric[idx],
reward: !prevState.metric[idx].reward
}
}
}))
}

但在这个函数运行后,一定有什么东西扰乱了状态配置,因为后面使用metric.map(val, idx)的函数失败了。

函数调用后的预期示例:

之前:

state = {
metric: [{name: "latency1", type:"counter", reward: false},
{name: "latency2", type:"counter", reward: false}]
}

调用SelectedChange(1(后:

state = {
metric: [{name: "latency1", type:"counter", reward: false},
{name: "latency2", type:"counter", reward: true}]
}

您将度量创建为数组,但在更改函数中为对象赋值。如果您想通过数组中项的索引来更改状态,可以使用spread运算符复制状态并将其分配给新变量,更新它并将其传递给onSelectedChange函数中的setState。例如:

let metric = [...this.state.metric];
metric[idx] = { ...metric[idx], reward: true };
this.setState({
metric
});

尝试这样做:

onSelectedChange = (idx) => {
let newMetricArr = this.state.metric.map((metric,i) => {
if (i === idx) {
return {
...metric,
reward: !metric.reward
}
}
return metric;
})
this.setState({metric: newMetricArr})
}

最新更新