Redux:为什么避免突变是使用它的一个基本部分? [英] Redux: Why is avoiding mutations such a fundamental part of using it?

查看:28
本文介绍了Redux:为什么避免突变是使用它的一个基本部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Redux 的新手 - 我真的想了解使用函数式编程使单向数据更优雅的大局.

I'm new to Redux - and I'm really trying to get the big picture of using functional programming to make unidirectional data more elegant.

我的看法 - 每个 reducer 都采用旧状态,在不改变旧状态的情况下创建一个新状态,然后将新状态传递给下一个 reducer 以执行相同的操作.

The way I see it- each reducer is taking the old state, creating a new state without mutating the old state and then passing off the new state to the next reducer to do the same.

我知道不会造成副作用有助于我们获得单向数据流的好处.

I get that not causing side effects helps us get the benefits of a unidirectional flow of data.

我真的不明白不改变旧状态有什么那么重要.

我唯一能想到的可能是我读过的时间旅行",因为如果你坚持每一个状态,你就可以执行和撤消".

The only thing I can think of is maybe the "Time-Traveling" I've read about because, if you held on to every state, you could perform and "undo".

问题:

我们不想在每一步都改变旧状态还有其他原因吗?

Are there other reasons why we don't want to mutate the old state at each step?

推荐答案

如果处理得当,使用不可变数据结构可以对性能产生积极影响.在 React 的情况下,如果数据没有改变,性能通常是为了避免不必要的应用重新渲染.

Working with immutable data structures can have a positive impact on performance, if done right. In the case of React, performance often is about avoiding unnecessary re-rendering of your app, if the data did not change.

要实现这一点,您需要将应用的下一个状态与当前状态进行比较.如果状态不同:重新渲染.否则不要.

To achieve that, you need to compare the next state of your app with the current state. If the states differ: re-render. Otherwise don't.

要比较状态,您需要比较状态中的对象是否相等.在普通的旧 JavaScript 对象中,您需要深入比较以查看对象内的任何属性是否发生了变化.

To compare states, you need to compare the objects in the state for equality. In plain old JavaScript objects, you would need to deep compare in order to see if any property inside the objects changed.

对于不可变对象,您不需要那个.

With immutable objects, you don't need that.

immutableObject1 === immutableObject2

基本上可以解决问题.或者,如果您使用的是像 Immutable.js Immutable.is(obj1, obj2).

basically does the trick. Or if you are using a lib like Immutable.js Immutable.is(obj1, obj2).

就反应而言,您可以将其用于 shouldComponentUpdate 方法,就像流行的 PureRenderMixin 一样.

In terms of react, you could use it for the shouldComponentUpdate method, like the popular PureRenderMixin does.

shouldComponentUpdate(nextProps, nextState) {
    return nextState !== this.state;
}

当状态没有改变时,这个函数可以防止重新渲染.

This function prevents re-rendering, when the state did not change.

我希望,这有助于不可变对象背后的推理.

I hope, that contributes to the reasoning behind immutable objects.

这篇关于Redux:为什么避免突变是使用它的一个基本部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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