[英]Updating arrays that are part of a React state
I have a state that I have created and one of the properties of that sate is an array with an arbitrary number of values.我有一个我创建的 state 并且该状态的属性之一是具有任意数量值的数组。 Using setState functionality I can manipulate the array property in its entirety but what I want to do is dig into the property and change the Nth index of the array.使用 setState 功能,我可以完整地操作数组属性,但我想做的是深入研究该属性并更改数组的第 N 个索引。 I'm struggling with that and it almost seems like I need to just rebuild the whole array with whatever I want to change and then just swap the new array with the old one.我正在为此苦苦挣扎,似乎我只需要用我想要更改的任何内容重建整个阵列,然后将新阵列与旧阵列交换即可。
I'm struggling with that and it almost seems like I need to just rebuild the whole array with whatever I want to change and then just swap the new array with the old one.我正在为此苦苦挣扎,似乎我只需要用我想要更改的任何内容重建整个阵列,然后将新阵列与旧阵列交换即可。
Yes.是的。
Provide a new value to the set state function, don't mutate the state variable.为集合 state function 提供一个新值,不要改变 state 变量。
setMyState(
oldState.map((currentValue, index) => {
if (index === Nth) {
return newValue;
} else {
return currentValue;
}
})
)
You can also try你也可以试试
let newArray = [...this.state.array].map((a, index) => {
if (index === NthIndex) {
return newValue
}
return a
})
this.setState({ array: newArray })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.