react源码解析(四)React.Component()PureComponent()

源文件地址:packages/react/src/ReactBaseClasses.js

github地址

 * Base class helpers for the updating state of a component.
 * 相当于Es6
 * class Component {
 *   constructor(props, context, updater) {
 *    this.props = props
      this.context = context
      this.refs = emptyObject
      this.updater = updater || ReactNoopUpdateQueue 
 *   }
 * }
 *
 */
function Component(props, context, updater) {
  this.props = props;
  this.context = context;
  // 如果一个组件有字符串引用,我们将分配一个不同的对象
  this.refs = emptyObject;
  // We initialize the default updater but the real one gets injected by the
  // renderer.
  this.updater = updater || ReactNoopUpdateQueue;
}

// 用户判断是React.Component
Component.prototype.isReactComponent = {};

/**
 * @param {object|function} partialState
 * @param {?function} callback Called after state is updated.
 * @final
 * @protected
 * setState({
 *
 * }, callbck)
 */
// 在Component原型挂载setState
Component.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.',
  );
  // 执行setState
  this.updater.enqueueSetState(this, partialState, callback, 'setState');
};

/**
 * @param {?function} callback Called after update is complete.
 * @final
 * @protected
 */
// 在原型上面挂载forceUpdate
Component.prototype.forceUpdate = function(callback) {
  // 执行forceUpdate
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};

PureComponent

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

/**
 * PureComponent组件, 跟Component类似
 *
 * class PureComponent {
 *   constructor(props, context, updater) {
 *     this.props = props;
 *     this.context = context;
 *     this.refs = emptyObject;
 *     this.updater = updater || ReactNoopUpdateQqueue;
 *   }
 * }
 */
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;
}
// PureComponent的原型指向了一个空对象ComponentDummy,对象的原型指向了Component的原型
const pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
pureComponentPrototype.constructor = PureComponent;
// 避免这些方法的额外原型跳转
Object.assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;

export {Component, PureComponent};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值