我可以在 PureComponent 中使用 shouldComponentUpdate 吗

IT技术 javascript reactjs
2021-05-05 10:11:31

我知道的功能shouldComponentUpdate,以及PureComponent但是我想知道我是否可以同时使用两者?

假设我有很多props,我想让它们在PureComponent. 除了1个props,这需要巧妙地进行比较。那么可以shouldComponentUpdate用于它吗?React 会考虑哪个结果?

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

如果它是两层的就好了,如果PureComponent返回 false,则控件进入我的shouldComponentUpdate位置,我有另一个机会return false.

1个回答

您首先会在开发环境中收到警告,因为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,您将失去浅比较。