正确推入状态数组的方法 [英] Correct way to push into state array

查看:300
本文介绍了正确推入状态数组的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎在将数据推送到状态数组时遇到问题。
我试图通过这种方式实现它:

I seem to be having issues pushing data into a state array. I am trying to achieve it this way:

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

但我认为这是不正确的方式并导致可变性问题?

But I believe this is incorrect way and causes issues with mutability?

推荐答案

数组推送返回长度



this.state.myArray.push('new value')返回扩展数组的长度,而不是数组本身。

Array push returns length

this.state.myArray.push('new value') returns the length of the extended array, instead of the array itself.

https://developer.mozilla.org/en -US / docs / Web / JavaScript / Reference / Global_Objects / Array / push

我猜你期望返回的值是数组。

I guess you expect the returned value to be the array.

这似乎是React的行为:

It seems it's rather the behaviour of React:

不要直接改变this.state,因为之后调用setState()可能会
替换mut你做了什么。将this.state视为
immutable。

NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

https://facebook.github.io/react/docs/component-api.html

我想,你会这样做(不熟悉React):

I guess, you would do it like this (not familiar with React):

var joined = this.state.myArray.concat('new value');
this.setState({ myArray: joined })

这篇关于正确推入状态数组的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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