推入状态数组的正确方法数组推送返回长度不变性

2022-08-30 00:45:18

我似乎在将数据推送到状态数组时遇到问题。我试图以这种方式实现它:

this.setState({ myArray: this.state.myArray.push('new value') })

但我认为这是不正确的方式,并导致可变性问题?


答案 1

使用es6可以像这样完成:

this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array

跨页语法


答案 2

数组推送返回长度

this.state.myArray.push('new value')返回扩展数组的长度,而不是数组本身。Array.prototype.push().

我猜你期望返回的值是数组。

不变性

这似乎是 React 的行为:

切勿直接改变 this.state,因为之后调用 setState() 可能会替换您所做的突变。将 this.state 视为不可变。React.Component.

我想,你会这样做(不熟悉 React):

var joined = this.state.myArray.concat('new value');
this.setState({ myArray: joined })