我似乎在将数据推入状态数组时遇到问题。我正在尝试以这种方式实现它:
this.setState({ myArray: this.state.myArray.push('new value') })
但是我相信这是不正确的方式,并导致可变性问题?
this.state.myArray.push('new value')返回扩展数组的长度,而不是数组本身。Array.prototype.push()。
this.state.myArray.push('new value')
我猜您希望返回的值是数组。
似乎这是React的行为:
切勿直接更改this.state,因为此后调用setState()可能会替换您所做的更改。将此this.state视为不可变的。React.Component。
我猜,您会这样做(不熟悉React):
var joined = this.state.myArray.concat('new value'); this.setState({ myArray: joined })