浅比较如何在反应中工作 [英] How does shallow compare work in react

查看:17
本文介绍了浅比较如何在反应中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 React 的本文档中,据说><块引用>

shallowCompare 对当前 props 和 nextProps 对象以及当前 state 和 nextState 对象执行浅层相等性检查.

我无法理解的是,如果它对对象进行浅层比较,则 shouldComponentUpdate 方法将始终返回 true,如

<块引用>

我们不应该改变状态.

如果我们不改变状态,那么比较将始终返回 false,因此 shouldComponent 更新将始终返回 true.我对它是如何工作的以及我们将如何覆盖它以提高性能感到困惑.

解决方案

Shallow compare 确实会检查相等性.在比较标量值(数字、字符串)时,它会比较它们的值.在比较对象时,它不会比较它们的属性——只比较它们的引用(例如它们是否指向同一个对象?").

让我们考虑以下 user 对象的形状

user = {姓名:约翰",姓氏:Doe"}

示例 1:

const user = this.state.user;用户名 =简";console.log(user === this.state.user);//真的

请注意,您更改了用户名.即使有这种变化,对象也是相等的.参考文献完全相同.

示例 2:

const user = clone(this.state.user);console.log(user === this.state.user);//错误的

现在,如果对象属性没有任何变化,它们就完全不同了.通过克隆原始对象,您可以使用不同的引用创建一个新副本.

克隆函数可能看起来像这样(ES6 语法)

const clone = obj =>Object.assign({}, ...obj);

浅比较是检测变化的有效方法.它希望您不会改变数据.

In this documentation of React, it is said that

shallowCompare performs a shallow equality check on the current props and nextProps objects as well as the current state and nextState objects.

The thing which I am unable to understand is If It shallowly compares the objects then shouldComponentUpdate method will always return true, as

We should not mutate the states.

and if we are not mutating the states then the comparison will always return false and so the shouldComponent update will always return true. I am confused about how it is working and how will we override this to boost the performance.

解决方案

Shallow compare does check for equality. When comparing scalar values (numbers, strings) it compares their values. When comparing objects, it does not compare their attributes - only their references are compared (e.g. "do they point to same object?").

Let's consider the following shape of user object

user = {
  name: "John",
  surname: "Doe"
}

Example 1:

const user = this.state.user;
user.name = "Jane";

console.log(user === this.state.user); // true

Notice you changed users name. Even with this change, the objects are equal. The references are exactly the same.

Example 2:

const user = clone(this.state.user);
console.log(user === this.state.user); // false

Now, without any changes to object properties they are completely different. By cloning the original object, you create a new copy with a different reference.

Clone function might look like this (ES6 syntax)

const clone = obj => Object.assign({}, ...obj);

Shallow compare is an efficient way to detect changes. It expects you don't mutate data.

这篇关于浅比较如何在反应中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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