我在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}]
}
在调用onSelectedChange(1)之后:
state = {
metric: [{name: "latency1", type:"counter", reward: false},
{name: "latency2", type:"counter", reward: true}]
}
答案 0 :(得分:2)
您正在将指标创建为数组,但在更改函数中将其分配给对象。如果要通过数组中项目的索引更改状态,则可以使用传播运算符复制状态并将其分配给新变量,对其进行更新并将其传递给onSelectedChange函数中的setState。例如:
let metric = [...this.state.metric];
metric[idx] = { ...metric[idx], reward: true };
this.setState({
metric
});
答案 1 :(得分:0)
尝试这样做:
onSelectedChange = (idx) => {
let newMetricArr = this.state.metric.map((metric,i) => {
if (i === idx) {
return {
...metric,
reward: !metric.reward
}
}
return metric;
})
this.setState({metric: newMetricArr})
}