本文基于 v16.12.0 版本

组件
var FunctionComponent = 0;
var ClassComponent = 1;
var IndeterminateComponent = 2; //待定组件类型
Component 与 PureComponent
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.prototype.isReactComponent = {};
Component.prototype.setState = function (partialState, callback) {
if (
!(
typeof partialState === "object" ||
typeof partialState === "function" ||
partialState == null
)
) {
{
throw Error(
"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");
};
Component.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
};
function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;
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;
}
var pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.
objectAssign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;
总结
- Component 和 PureComponeny 的构造函数定义是一样的
- PureComponent.prototype 继承自 Component.prototype --原型式继承
- 为了减少一次原型链查找,把 Component.prototype 在 PureComponent.prototype 上复制了一份,这样的话,Component.prototype 中的方法在 PureComponent.prototype 中都有,无需再从
__proto__上查找了。 - 并在 PureComponent.prototype 上添加了关键的 isPureReactComponent 标示
PureComponent instanceof Component //false
PureComponent.prototype instanceof Component //true
Component.prototype.isPrototypeOf(PureComponent.prototype) // true
PureComponent.prototype.__proto__=== Component.prototype //true