首页 > 解决方案 > 覆盖 PureComponent 的 shouldComponentUpdate 的问题

问题描述

例如我想写这样的东西:

class MyComponent extends PureComponent {
  shouldComponentUpdate(nextProps, nextState, nextContext) {
    console.log('shouldComponentUpdate');
    return super.shouldComponentUpdate(nextProps, nextState, nextContext);
  }
}

但是 super.shouldComponentUpdate 是未定义的。

  1. 为什么 super.shouldComponentUpdate 未定义?
  2. 如何调用 PureComponent 的默认实现?

反应 16.0.0

标签: javascriptreactjsoverriding

解决方案


进一步扩展维克多的回应。React 中 PureComponent 和 Component 的区别在于,纯组件通过对 props 和 state 进行浅层比较来处理 shouldComponentUpdate。

如果您想提供自定义 shouldComponentUpdate 来处理何时以及何时不应该更新组件,我建议您只使用常规组件。我还要注意 PureComponent 和 Component 都需要一个构造函数,该构造函数将 super() 调用作为第一行。


推荐阅读