我似乎有问题将数据推入一个状态数组。 我正试图以这种方式实现它:
this.setState({ myArray: this.state.myArray.push('new value') })
但我相信这是不正确的方式,并导致问题的可变性?
我似乎有问题将数据推入一个状态数组。 我正试图以这种方式实现它:
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,'酒吧']。
其他回答
我想现在回答这个问题有点晚了,但对于那些新来的人来说
你可以使用这个叫做immer的小包
请看这个例子:https://immerjs.github.io/immer/produce
数组push返回长度
this.state.myArray。push('new value')返回扩展数组的长度,而不是数组本身。array .prototype.push()
我猜您希望返回值是数组。
不变性
这似乎是React的行为:
千万不要变异。直接调用setState() 替换您所做的突变。对待这个问题。就像它是那样的状态 immutable.React.Component。
我猜,你会这样做(不熟悉React):
var joined = this.state.myArray.concat('new value');
this.setState({ myArray: joined })
用下面的方法可以检查和更新对象
this.setState(prevState => ({
Chart: this.state.Chart.length !== 0 ? [...prevState.Chart,data[data.length - 1]] : data
}));
你可以使用.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] );