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