React源码解析:react-component

270 阅读2分钟

1. Component

/**
 * Base class helpers for the updating state of a component.
 */
function Component(props, context, updater) {
  this.props = props;
  this.context = context;
  // If a component has string refs, we will assign a different object later.
  this.refs = emptyObject;
  // We initialize the default updater but the real one gets injected by the
  // renderer.
  this.updater = updater || ReactNoopUpdateQueue;
}

Component组件主要实现了两个原型链方法:

  1. setState
  2. forceUpdate 两个方法均是基于updater实现。

注:如果没有被实例化并被挂载会用eactNoopUpdateQueue去实现。

updater:

  1. 我们可能并没有在react component使用到过,承载了实际的component更新操作。
  2. updater作为参数传入的原因是因为不同的平台用到的核心是一样的,但是具体的涉及到更新state要走的流程,更新state后要渲染及渲染的流程是跟平台有关,作为参数可以让不同的平台传入进来。

2. PureComponent

function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;

/**
 * Convenience component with default shallow equality check for sCU.
 */
function PureComponent(props, context, updater) {
  this.props = props;
  this.context = context;
  // If a component has string refs, we will assign a different object later.
  this.refs = emptyObject;
  this.updater = updater || ReactNoopUpdateQueue;
}

const pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
pureComponentPrototype.constructor = PureComponent;
// Avoid an extra prototype jump for these methods.
Object.assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;
  1. PureComponent的实现是通过ComponentDummy这个类去实现的,可以理解为PureComponent继承于Component。
  2. ComponentDummy类的作用是为了在修改PureComponent原型链方法时不会对Component造成影响。
  3. PureComponent与Component的区别在于在pureComponentPrototype上增加一个isPureReactComponent属性。

setState:

omponent.prototype.setState = function(partialState, callback) {
  invariant(
    typeof partialState === 'object' ||
      typeof partialState === 'function' ||
      partialState == null,
    'setState(...): takes an object of state variables to update or a ' +
      'function which returns an object of state variables.',
  );
  this.updater.enqueueSetState(this, partialState, callback, 'setState');
};

  1. partialState:状态,可以是对象或方法。
  2. invariant(...): 判断下是不是一个对象or方法or null,然后提示。
  3. this.updater.enqueueSetState(this, partialState, callback, 'setState'):对ReactNoopUpdateQueue的处理发出警告(具体的实现方法在react-dom)!

forceUpdate:

Component.prototype.forceUpdate = function(callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};
  1. 强制Component更新一遍,哪怕状态没有更新!
  2. 调用 forceUpdate() 将致使组件调用 render() 方法,此操作会跳过该组件的 shouldComponentUpdate()。但其子组件会触发正常的生命周期方法,包括 shouldComponentUpdate() 方法。如果标记发生变化,React 仍将只更新 DOM。