Javascript 推入状态数组的正确方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37435334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:20:00  来源:igfitidea点击:

Correct way to push into state array

javascriptreactjsimmutability

提问by Ilja

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?

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

回答by Aliaksandr Sushkevich

Using es6 it can be done like this:

使用 es6 可以这样完成:

this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array

Spread syntax

传播语法

回答by Márton Tamás

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

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

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

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

Immutability

不变性

It seems it's rather the behaviour of React:

这似乎是 React 的行为:

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.

永远不要直接改变 this.state,因为之后调用 setState() 可能会替换你所做的改变。将 this.state 视为不可变的。反应组件

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

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

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

回答by Hemadri Dasari

Never recommended to mutate the state directly.

从不建议直接改变状态。

The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:

在后面的 React 版本中推荐的方法是在修改状态时使用更新程序函数来防止竞争条件:

Push string to end of the array

将字符串推到数组的末尾

this.setState(prevState => ({
  myArray: [...prevState.myArray, "new value"]
}))

Push string to beginning of the array

将字符串推送到数组的开头

this.setState(prevState => ({
  myArray: ["new value", ...prevState.myArray]
}))

Push object to end of the array

将对象推送到数组的末尾

this.setState(prevState => ({
  myArray: [...prevState.myArray, {"name": "object"}]
}))

Push object to beginning of the array

将对象推送到数组的开头

this.setState(prevState => ({
  myArray: [ {"name": "object"}, ...prevState.myArray]
}))

回答by Christoph

You should not be operating the state at all. At least, not directly. If you want to update your array, you'll want to do something like this.

你根本不应该操作状态。至少,不是直接的。如果你想更新你的数组,你会想要做这样的事情。

var newStateArray = this.state.myArray.slice();
newStateArray.push('new value');
this.setState(myArray: newStateArray);

Working on the state object directly is not desirable. You can also take a look at React's immutability helpers.

直接处理状态对象是不可取的。您还可以查看 React 的不变性助手。

https://facebook.github.io/react/docs/update.html

https://facebook.github.io/react/docs/update.html

回答by Ginden

You can use .concatmethod to create copy of your array with new data:

您可以使用.concat方法用新数据创建数组的副本:

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

But beware of special behaviour of .concatmethod when passing arrays - [1, 2].concat(['foo', 3], 'bar')will result in [1, 2, 'foo', 3, 'bar'].

但是.concat在传递数组时要注意方法的特殊行为-[1, 2].concat(['foo', 3], 'bar')将导致[1, 2, 'foo', 3, 'bar'].

回答by Hamid Hosseinpour

This Code work for me :

此代码对我有用:

fetch('http://localhost:8080')
  .then(response => response.json())
  .then(json => {
  this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})

回答by Mahgol Fa

React-Native

反应原生

if u also want ur UI (ie. ur flatList) to be up to date, use PrevState: in the example below if user clicks on the button , it is going to add a new object to the list( both in the model and UI)

如果您还希望您的 UI(即您的 flatList)是最新的,请使用 PrevState:在下面的示例中,如果用户单击按钮,它将向列表中添加一个新对象(在模型和 UI 中) )

data: ['shopping','reading'] // declared in constructor
onPress={() => {this.setState((prevState, props) => {
return {data: [new obj].concat(prevState.data) };
})}}. 

回答by KARTHIKEYAN.A

In the following way we can check and update the objects

通过以下方式我们可以检查和更新对象

this.setState(prevState => ({
    Chart: this.state.Chart.length !== 0 ? [...prevState.Chart,data[data.length - 1]] : data
}));