您首先会在开发环境中收到警告,因为React 源代码会检查在处理 a 时是否定义了该方法PureComponent
:
if (
isPureComponent(Component) &&
typeof inst.shouldComponentUpdate !== 'undefined'
) {
warning(
false,
'%s has a method called shouldComponentUpdate(). ' +
'shouldComponentUpdate should not be used when extending React.PureComponent. ' +
'Please extend React.Component if shouldComponentUpdate is used.',
this.getName() || 'A pure component',
);
}
然后,在渲染时,如果定义了此方法,它实际上会跳过
甚至不检查组件是否为 aPureComponent
并使用您自己的实现。
if (inst.shouldComponentUpdate) {
if (__DEV__) {
shouldUpdate = measureLifeCyclePerf(
() => inst.shouldComponentUpdate(nextProps, nextState, nextContext),
this._debugID,
'shouldComponentUpdate',
);
} else {
shouldUpdate = inst.shouldComponentUpdate(
nextProps,
nextState,
nextContext,
);
}
} else {
if (this._compositeType === ReactCompositeComponentTypes.PureClass) {
shouldUpdate =
!shallowEqual(prevProps, nextProps) ||
!shallowEqual(inst.state, nextState);
}
}
因此,通过shouldComponentUpdate
在 a 上实现您自己的PureComponent
,您将失去浅比较。