React.Component 源码思考

React.Component

https://github.com/facebook/react/blob/master/packages/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.
  this.updater = updater || ReactNoopUpdateQueue;
};

// 添加了判断传入的是否为 类 组件的标志。
Component.prototype.isReactComponent = {};

// 定义更新状态的方法。
// setState 接受两个参数 partialState:可以是对象、函数,callback:回调。
// this.updater.enqueueSetState 会更新state对象(reactDom)。
// 为什么要挂载到 this.updater 上?由于不同的平台渲染的方式不同(eg: ReactDOM、ReactNative), 根据传入的 updater对象 来实现对渲染的一个定制方式。
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');
};

// 与setState类似,其实就是强制Component更新一遍,哪怕状态没有更新。
Component.prototype.forceUpdate = function(callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};

// 这个不常用,其实和 Component 是一样的,只不过它多了一 isPureReactComponent 
// = true 作用是在 React-dom中判断是否是个pure component,决定是否更新
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());
pureComponentPrototype.constructor = PureComponent;
Object.assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;
// 问题?

// 关于 invariant => 判断下是不是一个对象or方法,然后提示。
// 不太懂 源码 为啥 直接 给错,也不看看传的参数。
export default function invariant(condition, format, a, b, c, d, e, f) {
  throw new Error(
    'Internal React error: invariant() is meant to be replaced at compile ' +
      'time. There is no runtime version.',
  );
}
// 应该这样
export default function invariant(condition, format, a, b, c, d, e, f) {
  if(condition) return ;
  throw new Error(
    'Internal React error: invariant() is meant to be replaced at compile ' +
      'time. There is no runtime version.',
  );
}

大佬的更详细

猜你喜欢

转载自blog.csdn.net/qq_42387542/article/details/107658362
今日推荐