React.Component 对比 React.PureComponent

React.Component vs React.PureComponent

官方React docs声明“React.PureComponentshouldComponentUpdate()只是浅比较对象”,如果状态是"deep",建议不要这样做。

鉴于此,在创建 React 组件时,有什么理由更喜欢 React.PureComponent 吗?

问题:

阅读本文时出现问题 medium blog,如果有帮助的话。

React.PureComponentReact.Component 之间的主要区别是 PureComponent 对状态更改进行 浅层比较 。这意味着当比较标量值时它比较它们的值,但当比较对象时它只比较引用。它有助于提高应用程序的性能。

当你能满足以下任一条件时,你应该选择React.PureComponent

  • State/Props 应该是不可变对象
  • State/Props 不应该有层次结构
  • 你应该在数据改变时调用forceUpdate

如果您使用 React.PureComponent,您应该确保所有子组件也是纯的。

is there any performance impact in using React.component that we may consider going for React.PureComponent?

是的,它会提高您的应用程序性能(因为比较浅)

I am guessing shouldComponentUpdate() of Purecomponent performs only shallow comparisons . If this is the case can' t the said method used for deeper comparisons?

你猜对了。只要满足我上面提到的任何一个条件,就可以使用它。

"Furthermore, React.PureComponent's shouldComponentUpdate() skips prop updates for the whole component subtree" - Does this mean that prop changes are ignored?

是的,如果在浅层比较中找不到差异,道具的变化将被忽略。

ComponentPureComponent 有一个区别

PureComponentComponent 完全相同,只是它为您处理了 shouldComponentUpdate 方法。

当 props 或 state 发生变化时,PureComponent 将对 props 和 state 进行浅比较Component 另一方面,不会将当前道具和状态与开箱即用的下一个进行比较。因此,每当调用 shouldComponentUpdate 时,组件将默认重新渲染。

浅比较

当将之前的道具和状态与下一个进行比较时,浅层比较将检查基元是否具有相同的值(例如,1 等于 1 或 true 等于 true)并且引用在更复杂的 [=35] 之间是否相同=] 对象和数组等值。

来源:https://codeburst.io/when-to-use-component-or-purecomponent-a60cfad01a81

在我看来,主要区别在于组件每次 parent 重新渲染时都会重新渲染,无论组件的 props 和状态是否发生变化。

另一方面,如果纯组件 parent 重新渲染,则不会重新渲染,除非纯组件的属性(或状态)已更改。

例如,假设我们有一个具有 three-level 层次结构的组件树:parent、children 和 grandchildren。

当 parent 的 props 以只有一个 child 的 props 被改变的方式改变时,那么:

  • 如果所有组件都是常规组件,那么整个组件树都会重新渲染
  • 如果所有 children 和 grandchildren 都是纯组件,那么只有一个 child 会重新渲染,而它的 grandchildren 中的一个或全部,取决于他们的道具是否改变。 如果这个组件树中有很多组件,这可能意味着显着的性能提升。

然而,有时使用纯组件不会有任何影响。当 parent 从 redux store 接收到它的 props 并且需要对其 children 的 props 执行复杂的计算时,我遇到过这样的情况。 parent 使用平面列表来呈现其 children。

结果是,每次 redux 存储即使有一个小的变化,childrens 数据的整个 flatlist 数组都会重新计算。这意味着对于树中的每个组件,道具都是新的 objects,即使值没有改变。

在这种情况下,纯组件无济于事,如果需要重新渲染,只能通过使用常规组件并在 children 中检查 shouldComponentUpdate 来实现性能提升。

我认为 PureComponent 比 Regular Component 更高效。事实上,您不必编写太多代码,它会为您处理 shouldComponentUpdate() 方法。