源文件地址:packages/react/src/ReactBaseClasses.js
* 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};