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

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

问题描述

我似乎在将数据推入状态数组时遇到问题.我正在尝试以这种方式实现它:

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.prototype.push().

Array push returns length

this.state.myArray.push('new value') returns the length of the extended array, instead of the array itself.Array.prototype.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() 可能替换您所做的突变.把 this.state 当作是不可变.React.Component.

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

我猜,你会这样做(不熟悉 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天全站免登陆