我在 React 的 state
中有一个简单的数组,仅包含整数:
this.state = {
myArray: [1,2,3]
}
我正在尝试以不可变的方式替换值(值 2
应替换为 8
):
const valueToReplace = 2
const newValue = 8
const myArray = this.state.myArray
const arrayPosition = myArray.indexOf(valueToReplace)
const newArray = Object.assign([], myArray, {arrayPosition: newValue})
this.setState({myArray: newArray})
但我的方式不会改变 myArray
的状态。我认为我没有以正确的方式使用Object.assign
。
最佳答案
您可以使用Array.prototype.slice
复制数组,改变你的副本,然后分配它。由于您是创建一个新数组而不是修改现有数组,因此您仍然可以避免突变问题。
const valueToReplace = 2
const newValue = 8
const newArray = this.state.myArray.slice() // copy
const arrayPosition = newArray.indexOf(valueToReplace)
newArray[arrayPosition] = newValue
this.setState({myArray: newArray})
关于javascript - 替换状态中的数组元素(整数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43902449/