Arrays 更新setState中对象的嵌套数组
我有一个包含多个数组的数组,其中包含多个对象,我想更新对象中的任何值。我可以更新对象,但我的问题是,每当我更新数组中的任何对象时,父数组就变成了对象。我不想将数组更改为object。我正在共享我的代码、输出和预期输出Arrays 更新setState中对象的嵌套数组,arrays,reactjs,setstate,Arrays,Reactjs,Setstate,我有一个包含多个数组的数组,其中包含多个对象,我想更新对象中的任何值。我可以更新对象,但我的问题是,每当我更新数组中的任何对象时,父数组就变成了对象。我不想将数组更改为object。我正在共享我的代码、输出和预期输出 this.setState({ tempArray: { ...this.state.tempArray, [lineNo]: { ...this.state.tempArray[lin
this.setState({
tempArray: {
...this.state.tempArray,
[lineNo]: {
...this.state.tempArray[lineNo],
[pointNo]: {
...this.state.tempArray[lineNo][pointNo],
x:parseInt(x),
y:parseInt(y)
}
}
}
},
()=>{
console.log('callback tempArray',this.state.tempArray);
})
如果我将给定数组中的第一个数组x:7更改为x:10
[[{x:7,y:20}],[{x:50,y:60}],[{x:30,y:40}]]
我的输出是
[{x:10,y:20},[{x:50,y:60}],[{x:30,y:40}]]
但我的预期产出是
[[{x:10,y:20}],[{x:50,y:60}],[{x:30,y:40}]]
您正在将
[lineNo]
设置为对象。试着这样做:
tempArray: {
...this.state.tempArray,
[lineNo]: [ // <--- [ instead of {
...this.state.tempArray[lineNo],
[pointNo]: {
...this.state.tempArray[lineNo][pointNo],
x:parseInt(x),
y:parseInt(y)
}
]// <--- ] instead of }
}
tempArray:{
…this.state.temparay,
[lineNo]:[//给出错误。编译失败。/src/dotLine/index.js第131行:分析错误:意外标记129 |…this.state.tempArray[lineNo],130 |[pointNo]:{>131 |…this.state.tempArray[lineNo][pointNo],|^132 | x:parseInt(x),133 | y:parseInt(y)134 |}