工作生活

setState&forceUpdate 源码阅读

2019-07-02  本文已影响0人  我家小八真可爱

setState 调用了 this.updater.enqueueSetState 方法,enqueueSetState 主要是创建 update,然后将它放入更新队列,最后进入调度阶段。

Component.prototype.setState = function(partialState, callback) {
  // partialState 可以为对象,或者一个返回值为对象的函数
  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');
};

enqueueSetState(inst, payload, callback) {
  const fiber = getInstance(inst);
  const currentTime = requestCurrentTime();
  const expirationTime = computeExpirationForFiber(currentTime, fiber);

  const update = createUpdate(expirationTime);
  update.payload = payload; // 要更新的内容
  if (callback !== undefined && callback !== null) {
    update.callback = callback;
  }

  flushPassiveEffects();
  enqueueUpdate(fiber, update);
  scheduleWork(fiber, expirationTime);
}

forceUpdate 与 setState 几乎相同,不同是 forceUpdate 的 update.tag 为 ForceUpdate,且没有 payload 这个参数。

Component.prototype.forceUpdate = function(callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};

enqueueForceUpdate(inst, callback) {
    const fiber = getInstance(inst);
    const currentTime = requestCurrentTime();
    const expirationTime = computeExpirationForFiber(currentTime, fiber);

    const update = createUpdate(expirationTime);
    update.tag = ForceUpdate;

    if (callback !== undefined && callback !== null) {
      update.callback = callback;
    }

    flushPassiveEffects();
    enqueueUpdate(fiber, update);
    scheduleWork(fiber, expirationTime);
  }
上一篇下一篇

猜你喜欢

热点阅读