我知道 shouldComponentUpdate
和 PureComponent
的功能。但我想知道我是否可以同时使用这两者?
假设我有很多 Prop ,我想让 PureComponent
中的浅层比较句柄。除了 1 个 Prop ,需要巧妙地进行比较。那么是否可以使用 shouldComponentUpdate
呢? React 会考虑哪个结果?
换句话说,React 会调用 PureComponent
的浅比较然后调用我的 shouldComponentUpdate
吗?还是我的 shouldComponentUpdate
会覆盖原来的?
如果它是两层的就好了,如果 PureComponent
返回 false,控件就会进入我的 shouldComponentUpdate
,在那里我有另一个机会 return false
.
最佳答案
您首先会在开发环境中收到警告,如 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);
}
}
因此,通过在 PureComponent
上实现您自己的 shouldComponentUpdate
,您将失去浅层比较。
关于javascript - 我可以在 PureComponent 中使用 shouldComponentUpdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44515544/