我似乎有问题将数据推入一个状态数组。 我正试图以这种方式实现它:

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

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


当前回答

你可以使用.concat方法创建包含新数据的数组副本:

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

但是要注意.concat方法在传递数组-[1,2]时的特殊行为。concat(“foo”3,'酒吧')将导致(1、2、“foo”,3,'酒吧']。

其他回答

功能组件和反应钩子

const [array,setArray] = useState([]);

最后推值:

setArray(oldArray => [...oldArray,newValue] );

在开始时推值:

setArray(oldArray => [newValue,...oldArray] );

我想现在回答这个问题有点晚了,但对于那些新来的人来说

你可以使用这个叫做immer的小包

请看这个例子:https://immerjs.github.io/immer/produce

这条准则对我很有用:

fetch('http://localhost:8080')
  .then(response => response.json())
  .then(json => {
  this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})

使用es6可以这样做:

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

传播的语法

你可以使用.concat方法创建包含新数据的数组副本:

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

但是要注意.concat方法在传递数组-[1,2]时的特殊行为。concat(“foo”3,'酒吧')将导致(1、2、“foo”,3,'酒吧']。