react中对PureComponent的深度认识

谈react优化其中最重要的一个组件就是PureComponent,主要的特点就是当数据即使发生深层次的变化,PureComponent也不会更新而且影响到子组件。
那PureComponent和Component的之间的联系在哪里,以下是对react框架代码的一些理解。

一、都是从React.js中暴露出来, 删除多此次不相关代码

import {Component, PureComponent} from './ReactBaseClasses';


const React = {
  Children: {
    map,
    forEach,
    count,
    toArray,
    only,
  },

  createRef,
  Component,
  PureComponent,

 
};


export default React;

此处可以看到Component都是来自于ReactBaseClasses.js,这样就很有意思了。PureComponent其实就是继承自Component, 注意ComponentDummy个人理解为Component复制品

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

Component.prototype.isReactComponent = {};
//  这里就是很熟悉的setSate
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异步的,updater更新的是一个队列
  this.updater.enqueueSetState(this, partialState, callback, 'setState');
};

// 强制更新 
Component.prototype.forceUpdate = function(callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};
// 声明一个复制品Component,利用其原型继承Component的原型
function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;

// 申明PureComponent
function PureComponent(props, context, updater) {
  this.props = props;
  this.context = context;
 
  this.refs = emptyObject;
  this.updater = updater || ReactNoopUpdateQueue;
}
// PureComponent原型再继承,复制品Component
const pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
pureComponentPrototype.constructor = PureComponent;
// assign 浅复制 Component的原型到 PureComponent
Object.assign(pureComponentPrototype, Component.prototype);
// 这里就是 PureComponent 和 Component 的区别加入了一个 isPureReactComponent  = true
pureComponentPrototype.isPureReactComponent = true;

export {Component, PureComponent};

二、浅比较是怎么发生的
1、我们还是回到React.js 文件中React 包含方法

import {
  createElement,
  createFactory,
  cloneElement,
  isValidElement,
} from './ReactElement';
const React = {
  createElement: __DEV__ ? createElementWithValidation : createElement,
  cloneElement: __DEV__ ? cloneElementWithValidation : cloneElement,
  createFactory: __DEV__ ? createFactoryWithValidation : createFactory,
 }

2、在ReactElemene.js中通过createElement创建Element

import ReactCurrentOwner from './ReactCurrentOwner';

const ReactElement = function(type, key, ref, self, source, owner, props) {
  const element = {

    $$typeof: REACT_ELEMENT_TYPE,

    type: type,
    key: key,
    ref: ref,
    props: props,


    _owner: owner,
  };
  return element;
};

export function createElement(type, config, children) {
  let propName;

  const props = {};

  let key = null;
  let ref = null;
  let self = null;
  let source = null;

  if (config != null) {
    if (hasValidRef(config)) {
      ref = config.ref;
    }
    if (hasValidKey(config)) {
      key = '' + config.key;
    }

    self = config.__self === undefined ? null : config.__self;
    source = config.__source === undefined ? null : config.__source;
    // Remaining properties are added to a new props object
    for (propName in config) {
      if (
        hasOwnProperty.call(config, propName) &&
        !RESERVED_PROPS.hasOwnProperty(propName)
      ) {
        props[propName] = config[propName];
      }
    }
  }

  const childrenLength = arguments.length - 2;
  if (childrenLength === 1) {
    props.children = children;
  } else if (childrenLength > 1) {
    const childArray = Array(childrenLength);
    for (let i = 0; i < childrenLength; i++) {
      childArray[i] = arguments[i + 2];
    }
    props.children = childArray;
  }

  // Resolve default props
  if (type && type.defaultProps) {
    const defaultProps = type.defaultProps;
    for (propName in defaultProps) {
      if (props[propName] === undefined) {
        props[propName] = defaultProps[propName];
      }
    }
  }
  // 每一个新创建的element都同时返回ReactCurrentOwner,用于跟踪当前element
  return ReactElement(
    type,
    key,
    ref,
    self,
    source,
    ReactCurrentOwner.current,
    props,
  );
}

3、看到这里就明白了,创建的元素关联上Owner其实就是一个Fiber对象,在整个Fiber模块里就能发现其中的比较

import type {Fiber} from 'react-reconciler/src/ReactFiber';

const ReactCurrentOwner = {
  /**
   * @internal
   * @type {ReactComponent}
   */
  current: (null: null | Fiber),
};

export default ReactCurrentOwner;

4、ReactFiberClassComponent是否为PureComponent,其中ctor其实就是Component

function checkShouldComponentUpdate(
  workInProgress,
  ctor,
  oldProps,
  newProps,
  oldState,
  newState,
  nextContext,
) {
  const instance = workInProgress.stateNode;
  if (typeof instance.shouldComponentUpdate === 'function') {
    startPhaseTimer(workInProgress, 'shouldComponentUpdate');
    const shouldUpdate = instance.shouldComponentUpdate(
      newProps,
      newState,
      nextContext,
    );
    stopPhaseTimer();

   
    return shouldUpdate;
  }

  if (ctor.prototype && ctor.prototype.isPureReactComponent) {
    return (
      !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState)
    );
  }

  return true;
}

四、在Fiber最终执行后体现的是在ReactDOM中。和react-reconciler关联起来在ReactFiberBeginWork模块中调用ReactFiberClassComponent的方法

function beginWork(
  current: Fiber | null,
  workInProgress: Fiber,
  renderExpirationTime: ExpirationTime,
): Fiber | null {
  const updateExpirationTime = workInProgress.expirationTime;

  // Before entering the begin phase, clear the expiration time.
  workInProgress.expirationTime = NoWork;

  switch (workInProgress.tag) {
	// 不确定组件,其实就是刚开始创建的组件还未指定类型
	case IndeterminateComponent: {
    }
    // 懒加载组件
    case LazyComponent: {
    }
    // 函数式组件
    case FunctionComponent: {
    }
    // class组件具有什么周期
    case ClassComponent: {
      const Component = workInProgress.type;
      const unresolvedProps = workInProgress.pendingProps;
      const resolvedProps =
        workInProgress.elementType === Component
          ? unresolvedProps
          : resolveDefaultProps(Component, unresolvedProps);
      return updateClassComponent(
        current,
        workInProgress,
        Component,
        resolvedProps,
        renderExpirationTime,
      );
    }

  }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章