尝试在 this.state 中更新数组的一个元素时出现(预期的)错误,但看不出哪里出错了。我是否需要创建一个临时数组更新,然后将整个数组分配回状态
这基本上是我所拥有的
this.state = { array: ['a', 'b', 'c'] };
onBack() {
this.setState({
array[2]: 'something'
});
}
最佳答案
你不能像这样更新状态。
Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
阅读 React docs 。
你可以这样做:
let newArray = [...this.state.array];
newArray[2] = 'somethingElse';
this.setState({array: newArray});
上面的例子使用的是 Spread Syntax 。
有多种方法可以修改状态,但所有方法都应确保将数据视为不可变的。您可以阅读有关在 React here 中处理状态的更多信息
关于arrays - 更新状态数组中的一个值 react 原生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50603368/