javascript - 我可以在 PureComponent 中使用 shouldComponentUpdate

标签 javascript reactjs

我知道 shouldComponentUpdatePureComponent 的功能。但我想知道我是否可以同时使用这两者?

假设我有很多 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/

相关文章:

javascript - 范围更改时更改按钮颜色

javascript - 如何通过 Angular 2 中的路由名称获取绝对 Url?

javascript - 使用 Firefox native 消息进行异步 webRequest.onBeforeRequest URL 检查

javascript - 在reactjs上从父级的onClick更新状态子级

javascript - 我们可以在 CSS 中创建没有 Javascript 的 onclick 弹出窗口吗?

javascript - 如何通过 Angular 执行 Laravel Controller 方法

javascript - 是否有可能在 react 组件标签之间传递文本?

javascript - 使用 ES6 扩展运算符 react props 语法

reactjs - react_toastify__WEBPACK_IMPORTED_MODULE_3__.toast.configure 不是一个函数

javascript - 在 react 中处理用户输入。如何将 [e.target.name] 连接到另一个字符串