React.Component 与 React.PureComponent
通常创建组件时,我们会继承Component
如下所示,这时我们可通过shouldComponentUpdate
方法进行条件渲染。当props与state发现改变时,就会进入shouldComponentUpdate
,当该方法返回true
时,则进行重新渲染。
import React, { Component } from 'react'
class myComp extends Component{
shouldComponentUpdate(nextProps, nextState) {
return true
}
render(){
return (<><div>Hellow World!</div></>)
}
}
而继承PureCompoent又是怎么用的呢?
1、继承PureComponent时,不能再重写shouldComponentUpdate
2、继承PureComponent时,进行的是浅比较,也就是说,如果是引用类型的数据,只会比较是不是同一个地址,而不会比较具体这个地址存的数据是否完全一致
3、浅比较会忽略属性或状态突变的情况,其实也就是,数据引用指针没变而数据被改变的时候,也不新渲染组件。但其实很大程度上,我们是希望重新渲染的。所以,这就需要开发者自己保证避免数据突变。
所以使用PureComponent很明显,可以提高性能,减低没必要的渲染工作