跳到主要内容

认识

2023年12月28日
柏拉文
越努力,越幸运

一、认识


PureComponent 内部是如何工作的呢,首先当选择基于 PureComponent 继承的组件。原型链上会有 isPureReactComponent 属性,代码如下:

react/src/ReactBaseClasses.js
/* pureComponentPrototype 纯组件构造函数的 prototype 对象,绑定isPureReactComponent 属性。 */
pureComponentPrototype.isPureReactComponent = true;

isPureReactComponent 这个属性在更新组件 updateClassInstance 方法中使用的。这个函数在更新组件的时候被调用,在这个函数内部,有一个专门负责检查是否更新的函数 checkShouldComponentUpdate

react/react-reconciler/ReactFiberClassComponent.js
function checkShouldComponentUpdate(){
if (typeof instance.shouldComponentUpdate === 'function') {
return instance.shouldComponentUpdate(newProps,newState,nextContext) /* shouldComponentUpdate 逻辑 */
}
if (ctor.prototype && ctor.prototype.isPureReactComponent) {
return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState)
}
}
  • isPureReactComponent 就是判断当前组件是不是纯组件的,如果是 PureComponent 会浅比较 propsstate 是否相等

  • shouldComponentUpdate 的权重,会大于 PureComponent

二、细节


思路 通过在shouldComponent(newProps,newState)生命周期中浅比较新旧状态,如果不相等,那就返回true

function shallowEqual(obj1, obj2) {
if (obj1 === obj2) {
return true;
}
if (
typeof obj1 !== "object" ||
obj1 == null ||
typeof obj2 !== "object" ||
obj2 == null
) {
return false;
}
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) {
return false;
}
for (let key of keys1) {
if (!obj2.hasOwnProperty(key) || obj1[key] !== obj2[key]) {
return false;
}
}
return true;
}
export class PureComponent extends React.Component {
shouldComponentUpdate(newProps, newState) {
return (
!shallowEqual(this.props, newProps) || !shallowEqual(this.state, newState)
);
}
}