替换状态中的数组元素(整数)
Replace array element (integer) in state
我在 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})
最好先创建一个数组的克隆,然后替换值:
const valueToReplace = 2
const newValue = 8
const myArray = this.state.myArray.slice(0);
const arrayPosition = myArray.indexOf(valueToReplace)
myArray[arrayPosition] = newValue
this.setState({myArray: newArray})
Object.assign
只是将 object/array 克隆到另一个变量中,并没有改变数组中的值。
我在 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})
最好先创建一个数组的克隆,然后替换值:
const valueToReplace = 2
const newValue = 8
const myArray = this.state.myArray.slice(0);
const arrayPosition = myArray.indexOf(valueToReplace)
myArray[arrayPosition] = newValue
this.setState({myArray: newArray})
Object.assign
只是将 object/array 克隆到另一个变量中,并没有改变数组中的值。