react 状态不变_React概念:不变性

react 状态不变

One concept you will likely meet when programming in React is immutability (and its opposite, mutability).

在React中进行编程时,您可能会遇到的一个概念是不变性(与之相反,就是可变性)。

It’s a controversial topic, but whatever you might think about the concept of immutability, React and most of its ecosystem kind of forces this, so you need to at least have a grasp of why it’s so important and the implications of it.

这是一个有争议的话题,但是无论您如何考虑不变性的概念,React及其大多数生态系统类型的力量,因此,您至少需要了解为什么它如此重要及其含义。

In programming, a variable is immutable when its value cannot change after it’s created.

在编程中,如果变量的值在创建后无法更改,则该变量是不可变的。

You are already using immutable variables without knowing it when you manipulate a string. Strings are immutable by default, when you change them in reality you create a new string and assign it to the same variable name.

您已经在使用不可变变量,而在操作字符串时却不知道它。 默认情况下,字符串是不可变的,在实际中更改它们时,您将创建一个新的字符串并将其分配给相同的变量名称。

An immutable variable can never be changed. To update its value, you create a new variable.

不可变的变量永远不能更改。 要更新其值,请创建一个新变量。

The same applies to objects and arrays.

对象和数组也是如此。

Instead of changing an array, to add a new item you create a new array by concatenating the old array, plus the new item.

要添加新项,而不是更改数组,您可以通过串联旧数组和新项来创建新数组。

An object is never updated, but copied before changing it.

对象从不更新,但在更改之前先进行复制。

This applies to React in many places.

这在许多地方都适用于React。

For example, you should never mutate the state property of a component directly, but only through the setState() method.

例如,永远不要直接setState()组件的state属性,而只能通过setState()方法。

In Redux, you never mutate the state directly, but only through reducers, which are functions.

Redux中 ,您永远不会直接改变状态,而只能通过化简器(即功能)进行改变。

The question is, why?

问题是,为什么?

There are various reasons, the most important of which are:

有多种原因,其中最重要的是:

  • Mutations can be centralized, like in the case of Redux, which improves your debugging capabilities and reduces sources of errors.

    突变可以集中化,例如Redux,可以提高调试功能并减少错误源。
  • Code looks cleaner and simpler to understand. You never expect a function to change some value without you knowing, which gives you predictability. When a function does not mutate objects but just returns a new object, it’s called a pure function.

    代码看起来更简洁易懂。 您永远不会期望函数会在您不知情的情况下更改某些值,从而使您具有可预测性 。 当一个函数不改变对象而只返回一个新对象时,它被称为纯函数。

  • The library can optimize the code because for example JavaScript is faster when swapping an old object reference for an entirely new object, rather than mutating an existing object. This gives you performance.

    该库可以优化代码,因为例如在将旧对象引用替换为全新对象而不是对现有对象进行突变时,JavaScript更快。 这给您表现

翻译自: https://flaviocopes.com/react-immutability/

react 状态不变

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值