React源码解析系列(三) —— React.Component

本文探讨React.Component的内部机制,揭示setState和forceUpdate的实际执行逻辑,同时解析PureComponent如何通过isPureReactComponent标记位优化渲染性能。
摘要由CSDN通过智能技术生成

我们平常写的class组件都需要继承React.Component这个基类,从而在类都实例中能使用相应的方法。下面让我们看看React.Component这个类究竟长什么样。

Component

const emptyObject = {};

function Component(props, context, updater) {
  this.props = props;
  this.context = context;
  // 用于保存render方法return出来的组件里的ref,一开始初始化为空对象
  this.refs = emptyObject;
  // 这个是组件更新时调用的更新方法,一开始初始化为空的方法类,需要后续注入。
  // 这样设计是为了能跨平台,如React-DOM实现一套更新方法,React-Native实现一套更新方法
  this.updater = updater || ReactNoopUpdateQueue;
}
// 这是一个标记位,用于后续判断class是否是React.Component
Component.prototype.isReactComponent = {};

Component.prototype.setState = function(partialState, callback) {
  // 这里调用后续注入进来的更新方法类来执行setState方法
  this.updater.enqueueSetState(this, partialState, callback, 'setState');
};

Component.prototype.forceUpdate = function(callback) {
  // 这里调用后续注入进来的更新方法类来执行forceUpdate方法
  this.updater.enqueueForceUpdate(this, callb
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值