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

查看:44
本文介绍了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?

制作数组副本的替代方法,以及看起来很浪费的 setStateing.

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

推荐答案

React文档 说:

将 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天全站免登陆