ReactComponent

本文详细解析React中的Component和PureComponent的实现原理,包括状态管理和强制更新的机制,以及不同平台的更新策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

React系列(3) ReactComponent

react/src/ReactBaseClasses.js

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.

  // update涉及渲染,react相同,react-dom平台与react-native平台的更新实现的具体方法不同,所以传入updater为不同平台定制自己不同的实现方式
  this.updater = updater || ReactNoopUpdateQueue;
}
Component.prototype.isReactComponent = {};

Component.prototype.setState = function(partialState, callback) {
  invariant( // 如果partialState不是object或方法或null,则提示信息
    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.',
  );
  // 调用初始化Component时,传入的对象updater上的enqueueSetState方法
  this.updater.enqueueSetState(this, partialState, callback, 'setState');
};

Component.prototype.forceUpdate = function(callback) {
  // 调用传入的updater上的enqueueForceUpdate,强制更新state
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};

Component会传入updater,updater根据平台不同会传入不同平台各自的updater对象

Component的原型上增加了setState,接收两个参数

  • partialState 仅为对象或者函数或者null,否则提示信息
  • callback setState的回调函数
    调用之前传入的updater对象的enqueueSetState方法

原型上还增加了forceUpadate,用于强制更新,接收参数为callback,调用了updater的enqueueForceUpdate方法

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()); // 继承Component
pureComponentPrototype.constructor = PureComponent;
// Avoid an extra prototype jump for these methods.
Object.assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true; // 与Component的唯一区别

pureComponent基本是继承了Component,与Component的唯一区别是有isPureReactComponent属性并且为true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值