gpt4 book ai didi

javascript - 浅比较如何在 react 中工作

转载 作者:IT王子 更新时间:2023-10-29 02:50:51 26 4
gpt4 key购买 nike

this documentation React的,据说

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

我无法理解的是,如果它浅比较对象,那么 shouldComponentUpdate 方法将始终返回 true,因为

We should not mutate the states.

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

最佳答案

浅比较会检查是否相等。比较标量值(数字、字符串)时,它会比较它们的值。比较对象时,它不会比较它们的属性 - 只会比较它们的引用(例如“它们指向同一个对象吗?”)。

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

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

示例 1:

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

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

请注意您更改了用户名。即使有这种变化,对象也是平等的。引用完全相同。

示例 2:

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

现在,如果不对对象属性进行任何更改,它们就完全不同了。通过克隆原始对象,您可以创建一个具有不同引用的新副本。

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

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

浅比较是一种检测变化的有效方法。它希望您不要改变数据。

关于javascript - 浅比较如何在 react 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36084515/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com