React
提供了一种基于浅比较模式来肯定是否应该从新渲染组件的类React.PureComponent
,一般只须要继承React.PureComponent
就能够定义一个纯组件。React.PureComponent
与React.Component
很类似,二者的区别在于React.Component
并未实现shouldComponentUpdate()
,而React.PureComponent
中以浅层对比prop
和state
的方式来实现了该函数。若是赋予React
组件相同的props
和state
,render()
函数会渲染相同的内容,那么在某些状况下使用React.PureComponent
可提升性能。javascript
首先咱们来回顾下React
组件执行重渲染re-render
更新的时机,通常当一个组件的props
属性或者state
状态发生改变的时候,也就是父组件传递进来的props
发生变化或者使用this.setState
函数时,组件会进行从新渲染re-render
。而在接受到新的props
或者state
到组件更新之间会执行其生命周期中的一个函数shouldComponentUpdate
,当该函数返回true
时才会进行重渲染,若是返回false
则不会进行重渲染,在这里shouldComponentUpdate
默认返回true
,所以当组件遇到性能瓶颈的时候能够在shouldComponentUpdate
中进行逻辑判断,来自定义组件是否须要重渲染。
咱们能够稍微查看一下源码的实现,能够看到PureComponent
是经过寄生组合继承的方式继承了Component
,commit id
为 0cf22a5
。html
// master/packages/react/src/ReactBaseClasses.js line 123 // ... function ComponentDummy() {} ComponentDummy.prototype = Component.prototype; /** * Convenience component with default shallow equality check for sCU. */ function PureComponent(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } const pureComponentPrototype = (PureComponent.prototype = new ComponentDummy()); pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods. Object.assign(pureComponentPrototype, Component.prototype); pureComponentPrototype.isPureReactComponent = true; // ...
同时在checkShouldComponentUpdate
函数中有一段这样的逻辑,在函数名上就能看出是对传入的参数进行了一次浅比较,所以实际上PureReactComponent
组件和ReactComponent
组件的区别就是React.PureComponent
中以浅层对比prop
和state
的方式来实现了shouldComponentUpdate()
函数。java
// master/packages/react-reconciler/src/ReactFiberClassComponent.new.js line 334 // ... if (ctor.prototype && ctor.prototype.isPureReactComponent) { return ( !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState) ); } // ...
须要注意的是,React.PureComponent
中的shouldComponentUpdate()
仅做对象的浅层比较。若是对象中包含复杂的数据结构,则有可能由于没法检查深层的差异,产生错误的比对结果。仅在你的props
和state
较为简单时才使用React.PureComponent
,或者每次更新都使用新的对象,或者在深层数据结构发生变化时调用forceUpdate()
来确保组件被正确地更新,你也能够考虑使用immutable
对象加速嵌套数据的比较。此外React.PureComponent
中的shouldComponentUpdate()
将跳过全部子组件树的prop
更新,所以须要确保全部子组件也都是纯的组件。react
shouldComponentUpdate
生命周期作了优化会自动shadow diff
组件的state
和props
,结合immutable
数据就能够很好地去作更新判断。shouldComponentUpdate
中的shadow diff
一样消耗性能。props
与state
。https://github.com/WindrunnerMax/EveryDay
https://zhuanlan.zhihu.com/p/30659051 https://juejin.cn/post/6844903618848669709 https://juejin.cn/post/6844904099679305741 https://segmentfault.com/a/1190000014979065 https://ginnko.github.io/2018/12/17/pure-component/ https://zh-hans.reactjs.org/docs/react-api.html#reactpurecomponent