React-Fiber 手写实现,源码理解(4)


theme: smartblue
highlight: a11y-dark

开篇

上一篇文章讲的是react-reconciler核心fiber构建逻辑,然后这一节就分析一下在注册任务之后的scheduler调度逻辑,如果你对一个整体框架源码的阅读逻辑有所疑问可以去看看第一篇文章。然后我们一边去分析源码的时候一边去收集问题,等到最后对源码有个大致的概括了之后,我们再一一去找出问题的答案。

思考

昨天听了一下coco大佬的会,我觉得很值得反思,就是你说看源码把其实只是一个最简单的一部分,很多时候把源码拿过来写点注释他是做什么的并不难,重要的是你思考的过程和到底为什么源码这么做,源码以前的实现方案可能会有什么问题等,我觉得这是一个难能可贵的事情,就前面的文章都是大篇描绘源码在做什么,可能后面的源码理解会更多的带有一些个人感情的思考过程。

源码分析

首先是调度原理核心这里可以看这里,感觉这部分其实是完全可以当做一个单独的包来看的,这里我们就不用去讲它了,我们现在去看源码任务调度的实现。

1.任务队列的管理

在开始的时候我们定义了两个数组,一个最小顶堆数组,一个延时任务数组。这里我们可以去收集2个问题,1:为什么要定义小顶堆数组。2:这个延时队列数组是用来干啥的。

// Tasks are stored on a min heap
var taskQueue = [];
var timerQueue = [];

接下来我们书接上文注册任务中ensureRootIsScheduledscheduleCallback,这个函数是用来注册回调任务,它接收一个优先级,回调函数(珂里化之后的),以及第三个参数延时回调相关(但实际上我们可以暂时在17里不分析它,因为没用到)。

// 省略代码
function unstable_scheduleCallback(priorityLevel, callback, options) {
  // 当前时间
  var currentTime = getCurrentTime();
  var startTime;
  if (typeof options === 'object' && options !== null) {
    // 忽略代码,延时相关
  } else {
    startTime = currentTime;
  }
  //  根据传入的优先级, 设置任务的过期时间expirationTime,这个过期时间指的是超过了这个时间这个回调就必须去执行了,他不能被一直打断。
  var timeout;
  switch (priorityLevel) {
    case ImmediatePriority:
      timeout = IMMEDIATE_PRIORITY_TIMEOUT;
      break;
    case UserBlockingPriority:
      timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
      break;
    case IdlePriority:
      timeout = IDLE_PRIORITY_TIMEOUT;
      break;
    case LowPriority:
      timeout = LOW_PRIORITY_TIMEOUT;
      break;
    case NormalPriority:
    default:
      timeout = NORMAL_PRIORITY_TIMEOUT;
      break;
  }
  var expirationTime = startTime + timeout;
  //  创建新任务
  var newTask = {
    id: taskIdCounter++,
    callback,
    priorityLevel,
    startTime,
    expirationTime,
    sortIndex: -1,
  };
  if (startTime > currentTime) {
    // 延时队列相关
  } else {
    // 好这句代码很关键,这有助于帮我们去解决问题1
    newTask.sortIndex = expirationTime;
    // 加入任务队列
    push(taskQueue, newTask);
    // 请求调度
    if (!isHostCallbackScheduled && !isPerformingWork) {
      isHostCallbackScheduled = true;
      requestHostCallback(flushWork);
    }
  }
  return newTask;
}

紧接着我们就可以走到requestHostCallback(flushWork),这里那就已经走到那个单独的包里了,注册包里的任务scheduledHostCallback = flushWork,那么我们最后执行的实际就是flushWork,我们就直接去看flushWork做了些什么。

function flushWork(hasTimeRemaining, initialTime) {
  // 忽略性能统计
  // 全局标记已经进入调度阶段了
  isHostCallbackScheduled = false;
  // 17.02忽略延迟队列处理

  isPerformingWork = true;
  const previousPriorityLevel = currentPriorityLevel;
  try {
    if (enableProfiling) {
      try {
        return workLoop(hasTimeRemaining, initialTime);
      } catch (error) {
        if (currentTask !== null) {
          const currentTime = getCurrentTime();
          markTaskErrored(currentTask, currentTime);
          currentTask.isQueued = false;
        }
        throw error;
      }
    } else {
      // 消费队列
      return workLoop(hasTimeRemaining, initialTime);
    }
  } finally {
    // 还原
    currentTask = null;
    currentPriorityLevel = previousPriorityLevel;
    isPerformingWork = false;
    // 忽略性能统计
  }
}

这整段代码的重点就是控制全局的状态,以及去消费队列,我们可以直接可以看消费队列workLoop那里。

function workLoop(hasTimeRemaining, initialTime) {
  let currentTime = initialTime; // 保存当前时间, 用于判断任务是否过期
  currentTask = peek(taskQueue); // 获取队列中的第一个任务
  while (currentTask !== null) {
    if (
      currentTask.expirationTime > currentTime &&
      (!hasTimeRemaining || shouldYieldToHost())
    ) {
      // 虽然currentTask没有过期, 但是执行时间超过了限制,停止继续执行, 让出主线程
      break;
    }
    const callback = currentTask.callback;
    if (typeof callback === 'function') {
      currentTask.callback = null;
      currentPriorityLevel = currentTask.priorityLevel;
      const didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
      // 执行回调,我觉得这里的入参是没有上装的功能,因为callback已经强制把root绑定了,这里实际传参数进去挤到第二个去了
      const continuationCallback = callback(didUserCallbackTimeout);
      currentTime = getCurrentTime();
      // 回调完成, 判断是否还有连续回调
      if (typeof continuationCallback === 'function') {
        // 保留currentTask
        currentTask.callback = continuationCallback;
      } else {
        // 把currentTask移出队列
        if (currentTask === peek(taskQueue)) {
          pop(taskQueue);
        }
      }
    } else {
      // 如果任务被取消(这时currentTask.callback = null), 将其移出队列
      pop(taskQueue);
    }
    // 更新currentTask
    currentTask = peek(taskQueue);
  }
  if (currentTask !== null) {
    return true; // 如果task队列没有清空, 返回true. 等待调度中心下一次回调
  } else {
    return false; // task队列已经清空, 返回false.
  }
}

这里我们需要关注的是有一个点和收集到了一个问题:

1:循坏中断的条件:每次执行call前会以task来检测是否超时,否则就打断,数组完全被清空的时候也会被打断。
问题3: callback的传参问题。

到这我们已经可以暂时的告于段落了。接下来我们分析问题。

问题

问题1:为什么要定义小顶堆数组?

先看最小堆的实现
image.png
首先是选择堆这个不用多说O(1)的时间复杂度并且任务也确实是一个先进后出的过程,接下来是最小看到代码他每次pushpop(实际就是向上和向下的调整)的时候都会以一个过期时间从小到大的顺序(其实没看懂>>>运算符,但应该是一个O(n)的排序顺算,可以看看这个),调整整个堆(scheduleCallback中去定义了了顺序实际就是时间)的顺序。最后那这其实是为了取出优先级最高的任务,任务中的expirationTime越小就表示过期时间越近,该任务的优先级就越高。

问题2:字面意思,延时队列,时间到了就把任务扔到最小堆队列里面去。但17的源码里应该并不会往延时队列里扔东西进去。

function advanceTimers(currentTime: number) {
  // Check for tasks that are no longer delayed and add them to the queue.
  let timer = peek(timerQueue);
  while (timer !== null) {
    if (timer.callback === null) {
      // Timer was cancelled.
      pop(timerQueue);
    } else if (timer.startTime <= currentTime) {
      // Timer fired. Transfer to the task queue.
      pop(timerQueue);
      timer.sortIndex = timer.expirationTime;
      push(taskQueue, timer);
    } else {
      // Remaining timers are pending.
      return;
    }
    timer = peek(timerQueue);
  }
}

问题3callback的传参问题,这个地方我确实没看明白,他传了一个布尔值的参数过去,但实际上这边已经被bind了一个fiber了~

image.png

image.png

image.png

总结

学源码确实是一个很枯燥的事情,但是其实挺锻炼逻辑能力和写代码能力的,就感觉每次看完一个框架的源码和写完一个都是对自己能力的一个大提升,推荐一个渐进顺序vue源码=>react源码=>node交互层源码和一个长期一些我们常用包源码比如p-limit,axios,ajax等之类的。有问题可以+联系方式我们一起交流,一起卷,老生常谈一下,不是为了面试去学习,希望大家保持一颗学习的心,和写代码的热情。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容