如何将状态设置为数组以及如何使用setState和this.state访问它们

时间:2017-10-10 09:19:48

标签: javascript react-native

我创建了一个这样的数组:

state = {
    arr: [ ]
        }

我想更新状态以及访问它们

在我的功能中我想使用它像

func() {
    this.state.arr;   // for accesing the array 
     //remaining codes
    this.setState({arr: this.state.arr.push(2)}); //for updating 
     }

这导致错误和输出错误,使用

的代码有问题

1 个答案:

答案 0 :(得分:0)

看看Array.prototype.push():它返回新的长度而不是新数组。要获取新数组,您需要使用返回新数组实例的Array.prototype.concat()

this.setState({arr: this.state.arr.concat(2)});

另一方面,为什么需要this.state.arr;才能访问数组?你不是把它赋予任何变量等吗?

相关问题