在状态数组中添加值的最佳方法是什么 [英] What is the best way to add a value to an array in state

查看:71
本文介绍了在状态数组中添加值的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个状态数组,比如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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆