When to use Component or PureComponent?

PureComponent,React 15.3.0 新增
…prefer PureComponent over Component, but never mutate your objects.

[原文]https://codeburst.io/when-to-use-component-or-purecomponent-a60cfad01a81

React.PureComponent

pureComponent is being a more performant version of Component. This turned out to be true, but the performance gains come with a few strings attached.

  • 性能更好 !
  • 附加条件 ?
  • 场景:

我们有 2 个静态组件 Child,都被包含在一个父组件 Parent 里面:

import React from 'react';

class Parent extends React.Component {
	constructor() {}
	render() { return( 
		<Child1></> 
		<Child2></>
	) }
	componentWillUpdate() { console.log("parent will update...") }
}

class Child1 extends React.Component {
	render() { return( ) }
	componentWillUpdate() { console.log("child1 will update...") }
}

class Child1 extends React.PureComponent {
	render() { return( ) }
	componentWillUpdate() { console.log("child2 will update...") }
}
  1. 输出结果是:“parent will update…”、“child1 will update…”
  2. 虽然 Child1 组件没有任何 props 和 state 状态输入,只是一个静态组件,但跟着父组件 Parent 都重新渲染了;显然这是性能不好的
  3. Child2 不会重新渲染

1. 一点不同:with React.Component

PureComponent is exactly the same as Component except that it handles the shouldComponentUpdate method for you:PureComponent will do a shallow comparison on both props and state

  • shouldComponentUpdate

boolean shouldComponentUpdate(object nextProps, object nextState) 返回一个布尔值,false 表示不需要重新渲染,默认为 true。其在组件接收到新的 props 或者 state 时被执行。

  1. 使用 PureComponent 之后,组件在 shoudComponentUpdate 中会浅比较渲染前后的 props 和 state ,如果没有变化,组件不会进入接下来的生命周期,可以节省不必要的 diff 操作。

  2. 如果发现当前组件的 props 或 state 发生了变化,再 re-render

  3. Component 默认不会检查,因此每当 shouldComponentUpdate() 被调用组件都会 re-render

  4. 该函数在 Component 中是手动配置的;在 PureComponent 中是自动判断的。

  • 浅比较:shallow Comparison
  1. check that primitives have the same value:值发生改变就会发生渲染
  2. check that the references are the same between objects or arrays:需要引用不同才会渲染

2. 是否存在性能问题:Are there performance issues?

Comparing primitives and object references is an incredibly cheap operation.

If you have a list of child objects and one of the children updates, doing a check on their props and state is lightning fast compared to the cost of re-rendering each one.

所以在某些场景(如子组件作为展示组件,即 props 和 state 的改变并不是每次都会改变)使用 PureComponent 是能真正提升性能的。

猜你喜欢

转载自blog.csdn.net/hoanFir/article/details/87790617