你要首先在開發環境中得到一個警告爲React source code檢查,看是否該方法被定義或沒有時處理一個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',
);
}
然後,渲染時,如果這種方法被定義,它實際上會skip 甚至沒有檢查組件一個PureComponent
並使用您自己的實現。所以
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
上PureComponent
,你就失去了淺層比較。
我不認爲這是一個_probably_是OP在這裏尋找的! –