浅比较如何在反应中工作

编程入门 行业动态 更新时间:2024-10-28 10:32:04
本文介绍了浅比较如何在反应中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 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.

更多推荐

浅比较如何在反应中工作

本文发布于:2023-11-25 08:11:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628977.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   工作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!