gpt4 book ai didi

javascript - 这是 shouldComponentUpdate 的合理实现吗?

转载 作者:行者123 更新时间:2023-11-29 17:41:48 25 4
gpt4 key购买 nike

多年来我一直在使用 React,但从来没有实现 shouldComponentUpdate 的首选方法。嵌套 Prop 和状态的深度平等检查可能很困难。

但是,这样的事情有什么问题:

shouldComponentUpdate(nextProps, nextState) {
const propsChanged = JSON.stringify(this.props) !== JSON.stringify(nextProps)
const stateChanged = JSON.stringify(this.state) !== JSON.stringify(nextState)
return propsChanged || stateChanged
}

这样合适吗?这会以意想不到的方式失败吗?

我认为 JSON.stringify 和直接字符串比较也是非常快速的操作。

总的来说,这种方法对我来说似乎很合理,但我想知道我是否遗漏了任何明显的陷阱。

最佳答案

Would this fail in unexpected ways?

可能,而且它几乎肯定比进行深度对象遍历来确定相等性要慢(因为 JSON.stringify 必须进行深度对象遍历无论如何) .

它可能失败的一种方式是 JSON.stringify 可以为等效对象返回不同的字符串(这是指定的行为):

const o1 = {a: 1, b: 2};
const o2 = {b: 2, a: 1};
const str1 = JSON.stringify(o1);
const str2 = JSON.stringify(o2);
console.log(str1);
console.log(str2);
console.log(str1 === str2);

...尽管我承认在 React 组件中的 props 和 state 情况下(至少)这不太可能。 (当对象的非整数索引属性以不同的顺序创建时会发生这种情况。您的顶级 Prop 或状态属性可能不会发生这种情况,但从属对象呢?this.setState({foo}); 其中 foo 是在不同时间以不同方式创建的对象...)

关于javascript - 这是 shouldComponentUpdate 的合理实现吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52651471/

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