Component

  1. // Component 类构造函数
  2. function Component(props, context, updater) {
  3. // 初始化 props, context
  4. this.props = props;
  5. this.context = context;
  6. // If a component has string refs, we will assign a different object later.
  7. // 初始化 refs 为空对象
  8. this.refs = emptyObject;
  9. // We initialize the default updater but the real one gets injected by the
  10. // renderer.
  11. // 更新渲染用的函数 updater
  12. this.updater = updater || ReactNoopUpdateQueue;
  13. }
  14. // 用于判断当前函数是否是继承于 React.Component 的类组件
  15. Component.prototype.isReactComponent = {};
  16. Component.prototype.setState = function(partialState, callback) {
  17. // 类型校验
  18. invariant(
  19. typeof partialState === 'object' ||
  20. typeof partialState === 'function' ||
  21. partialState == null,
  22. 'setState(...): takes an object of state variables to update or a ' +
  23. 'function which returns an object of state variables.',
  24. );
  25. // 将数值更新操作入队
  26. this.updater.enqueueSetState(this, partialState, callback, 'setState');
  27. };
  28. Component.prototype.forceUpdate = function(callback) {
  29. // 将强制更新操作入队
  30. this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
  31. };

PureComponent

  1. function PureComponent(props, context, updater) {
  2. // 与 Component 一致
  3. this.props = props;
  4. this.context = context;
  5. // If a component has string refs, we will assign a different object later.
  6. this.refs = emptyObject;
  7. this.updater = updater || ReactNoopUpdateQueue;
  8. }
  9. // 一个跟 Component 完全一致的类(没有初始化的内容)
  10. function ComponentDummy() {}
  11. ComponentDummy.prototype = Component.prototype;
  12. // 实现 PureComponent extends Component
  13. const pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
  14. pureComponentPrototype.constructor = PureComponent;
  15. // Avoid an extra prototype jump for these methods.
  16. Object.assign(pureComponentPrototype, Component.prototype);
  17. // 判断当前组件是否是继承于 React.PureComponent 的类组件
  18. pureComponentPrototype.isPureReactComponent = true;