Javascript 如何对对象数组和prevState使用React-setstate方法?
我在React中配置了一个状态,它是一个对象数组:Javascript 如何对对象数组和prevState使用React-setstate方法?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我在React中配置了一个状态,它是一个对象数组: state = { metric: [{name: "", type:"", reward: false}], } 我希望在选中特定复选框时更新奖励属性(从false->true或true->false),我编写了一个onSelectedChange函数,该函数使用数组中的特定索引作为参数: onSelectedChange = (idx) => { this.setState((prevStat
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)
的函数失败了
函数调用后的预期示例:
之前:
调用所选更改(1)后:
您正在将度量创建为数组,但在更改函数中指定给对象。如果要通过数组中项目的索引更改状态,可以使用spread运算符复制状态并将其分配给新变量,更新状态并将其传递给onSelectedChange函数中的setState。e、 g:
let metric = [...this.state.metric];
metric[idx] = { ...metric[idx], reward: true };
this.setState({
metric
});
您正在将度量创建为数组,但在更改函数中指定给对象。如果要通过数组中项目的索引更改状态,可以使用spread运算符复制状态并将其分配给新变量,更新状态并将其传递给onSelectedChange函数中的setState。e、 g:
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})
}
尝试这样做:
onSelectedChange = (idx) => {
let newMetricArr = this.state.metric.map((metric,i) => {
if (i === idx) {
return {
...metric,
reward: !metric.reward
}
}
return metric;
})
this.setState({metric: newMetricArr})
}
如果要影响第一个对象。你应该这样使用它
onSelectedChange(0)
@Minan Right,但我的示例影响公制数组中的第二个元素,该元素具有索引1。如果要影响第一个对象。你应该这样使用它onSelectedChange(0)
@Minan Right,但我的示例影响到公制数组中的第二个元素,该元素具有索引1。在这种情况下,您将如何使用prevState更新奖励属性?因为每次单击复选框时,我都想在真与假之间切换。您可以使用以下选项切换奖励值:metric[idx]={…metric[idx],奖励:!metric[idx].raward}代码>在学习了更多关于JS的知识并做出了总体反应后,这个答案比我以前接受的答案更有效。非常感谢。在这种情况下,您将如何使用prevState更新奖励属性?因为每次单击复选框时,我都想在真与假之间切换。您可以使用以下选项切换奖励值:metric[idx]={…metric[idx],奖励:!metric[idx].raward}代码>在学习了更多关于JS的知识并做出了总体反应后,这个答案比我以前接受的答案更有效。非常感谢。