我可以在PureComponent中使用shouldComponentUpdate吗?

Sal*_*man 9 javascript reactjs

我知道功能shouldComponentUpdate以及PureComponent.但我想知道我是否可以将两者结合使用?

说我有很多道具,我想让浅层比较处理PureComponent.除了1道具,需要巧妙地进行比较.那么有可能用shouldComponentUpdate它吗?React会考虑哪个结果?

换句话说,React会调用PureComponent浅层比较然后调用我的shouldComponentUpdate吗?或者我shouldComponentUpdate会覆盖原来的?

如果它是双层的,如果PureComponent返回false,控制进入我shouldComponentUpdate有另一个机会的地方将会很好return false.

HiD*_*Deo 9

您将首先在开发环境中获取警告,因为React源代码检查以确定在处理时是否定义了方法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',
  );
}
Run Code Online (Sandbox Code Playgroud)

然后,在渲染时,如果定义了这个方法,它实际上会跳过 ,甚至不检查组件是否为a 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,通过shouldComponentUpdate在a上实现自己PureComponent,你将失去浅层比较.