【React源碼解讀】react-component

源碼在線地址:https://github.com/facebook/react/blob/master/packages/react/src/ReactBaseClasses.jsreact

// BaseReactClasses.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.
  this.updater = updater || ReactNoopUpdateQueue;
}

/**
props:,
context,
refs: 掛載節點在上面
updater: 咱們可能並無在react component使用到過,承載了實際的component更新操做
*/
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.',
  );
  this.updater.enqueueSetState(this, partialState, callback, 'setState');
};

/**
partialState: 一個狀態,能夠是一個對象or方法(後續更加推薦使用一個方法)
callback: 回調

invariant(...): 判斷下是否是一個對象or方法,而後提示

this.updater.enqueueSetState(this, partialState, callback, 'setState');
具體實現方法在react-dom中,具體學習會在react-dom中學習

爲何updater要做爲參數傳入進來?
不一樣的平臺,好比react-dom,react-native,用到的核心例如COmponet是同樣的,可是具體的涉及到更新state要走的流程,更新state後要渲染及渲染的流程是跟平臺有關的,做爲參數能夠讓不一樣的平臺傳入進來,定製
};
*/
Component.prototype.forceUpdate = function(callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};

/**
不經常使用,和setState相似,其實就是強制Component更新一遍,哪怕狀態沒有更新
*/
function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;


function PureComponent(props, context, updater) {
  this.props = props;
  this.context = context;
  
  this.refs = emptyObject;
  this.updater = updater || ReactNoopUpdateQueue;
}

const pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
pureComponentPrototype.constructor = PureComponent;

Object.assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;

/**
其實能夠認爲爲繼承於Component,使用ComponetDummy實現了一個簡單的繼承方式

唯一的區別就是在pureComponetPrototype上添加了一個isPureReactComponet屬性,使得在後續更新中,react-dom會去主動判斷是不是個pure component,決定是否更新
*/
相關文章
相關標籤/搜索