将值添加到状态数组的最佳方法是什么 [英] What is the best way to add a value to an array in state
本文介绍了将值添加到状态数组的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个状态数组,比如说 this.state.arr.我想为这个状态属性添加一些东西,然后再更改一些属性.
I have an array in state, let's say this.state.arr. I want to add something to this state property, and then change some more properties.
选项 1
onChange(event){
this.state.arr.push('newvalue');
...
this.setState({some:'val',arr:this.state.arr})
}
选项 2
onChange(event){
var newArr = this.state.arr;
...
newArr.push('newvalue');
...
this.setState({some:'val',arr:newArr})
}
所以.. 我知道 this.state 应该被视为不可变的.但是可以像在选项 1 中那样使用它,我仍然从中设置状态,或者我是否需要使用类似于选项 2 的东西,因此总是首先在内存中制作一个副本
So.. I know this.state is supposed to be treated immutable. But is it ok to use it like in option 1 where I still set the state from it, or do I need to go with something like option 2, and thus always first making a copy in memory
推荐答案
另一种使用 concat 的简单方法:
Another simple way using concat:
this.setState({
arr: this.state.arr.concat('new value')
})
这篇关于将值添加到状态数组的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文