在React.js中正确修改状态数组 [英] Correct modification of state arrays in React.js

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

问题描述

我想在state数组的末尾添加一个元素,这是正确的方法吗?

I want to add an element to the end of a state array, is this the correct way to do it?

this.state.arrayvar.push(newelement);
this.setState({ arrayvar:this.state.arrayvar });

我担心用push就地修改数组可能会引起麻烦-安全吗?

I'm concerned that modifying the array in-place with push might cause trouble - is it safe?

制作数组副本的替代方法,并且setState看起来很浪费.

The alternative of making a copy of the array, and setStateing that seems wasteful.

推荐答案

反应文档说:

将this.state视为不可变.

Treat this.state as if it were immutable.

您的push将直接更改状态,即使您此后再次重置"状态,也有可能导致易于出错的代码. F.ex,它可能导致某些生命周期方法(如componentDidUpdate)不会触发.

Your push will mutate the state directly and that could potentially lead to error prone code, even if you are "resetting" the state again afterwards. F.ex, it could lead to that some lifecycle methods like componentDidUpdate won’t trigger.

React更高版本中推荐的方法是在修改状态以防止竞争情况时使用 updater 函数:

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

this.setState(prevState => ({
  arrayvar: [...prevState.arrayvar, newelement]
}))

与使用非标准状态修改可能会遇到的错误相比,内存浪费"不是问题.

The memory "waste" is not an issue compared to the errors you might face using non-standard state modifications.

React早期版本的替代语法

您可以使用concat来获得简洁的语法,因为它会返回一个新数组:

You can use concat to get a clean syntax since it returns a new array:

this.setState({ 
  arrayvar: this.state.arrayvar.concat([newelement])
})

在ES6中,您可以使用 Spread Operator :

In ES6 you can use the Spread Operator:

this.setState({
  arrayvar: [...this.state.arrayvar, newelement]
})

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

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