jtwang7 / React-Note

React 学习笔记
8 stars 2 forks source link

浅谈 PureComponent 和 shouldComponentUpdate 间的关系 #34

Open jtwang7 opened 2 years ago

jtwang7 commented 2 years ago

参考文章:

shouldComponentUpdate 概述

React 组件默认会在内部状态发生改变时,重新渲染变化的组件,这个过程是 React 自身维护的。 shouldComponentUpdate 为开发者提供了一种手动控制 React 组件是否更新的手段,React 组件使用 shouldComponentUpdate 后,仅会在它返回 true 时对组件进行更新操作。有关 shouldComponentUpdate 的详细用法,可以参考 shouldComponentUpdate()

shouldComponentUpdate 返回 true 时,组件会被重新渲染,这一说法并不准确。 shouldComponentUpdate 决定是否更新虚拟 DOM,而真实 DOM 的重渲染是由 diff 算法来决定的,若一个组件和之前保留的状态相比并没有发生改变,即使它内部定义的 shouldComponentUpdate 返回了 true,也仅仅是重构了虚拟 DOM,真实 DOM 并不会被更新。

PureComponent

React.PureComponent 与 React.Component 很相似。两者的区别在于 React.Component 并未实现 shouldComponentUpdate(),而 React.PureComponent 中以浅层对比 prop 和 state 的方式来实现了 shouldComponentUpdate。

两者关系

PureComponent 本质上就是在 Component 基础上利用 shouldComponentUpdate 对 state 和 props 做浅比较,避免重复渲染未发生更改的组件。

不建议在 shouldComponentUpdate 中使用深比较的方式,这极可能导致性能问题。因此,我们要尽量避免深比较,最佳的实践就是将数据统一为 Immutable 不可变类型,避免可变类型的出现导致浅比较失效的问题。