解析 React 性能利器 — Fiber

{"type":"doc","content":[{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"什么是刷新率?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"大部分显示器屏幕都有固定的刷新率(比如最新的一般在 60Hz),所以浏览器更新最好是在 60fps。如果在两次硬件刷新之间浏览器进行两次重绘是没有意义的只会消耗性能。 浏览器会利用这个间隔 16ms(一帧)适当地对绘制进行节流,如果在 16ms 内做了太多事情,会阻塞渲染,造成页面卡顿, 因此 16ms 就成为页面渲染优化的一个关键时间。"}]},{"type":"horizontalrule"},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"一帧做了哪些事情"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.geekbang.org\/infoq\/d6\/d6c896c70ffd17c96a87438e0afc433a.webp","alt":"Image","title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"events"},{"type":"text","text":": 点击事件、键盘事件、滚动事件等"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"macro"},{"type":"text","text":": 宏任务,如 "},{"type":"codeinline","content":[{"type":"text","text":"setTimeout"}]}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"micro"},{"type":"text","text":": 微任务,如 "},{"type":"codeinline","content":[{"type":"text","text":"Promise"}]}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"rAF"},{"type":"text","text":": "},{"type":"text","marks":[{"type":"strong"}],"text":"requestAnimationFrame"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"Layout"},{"type":"text","text":": CSS 计算,页面布局"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"Paint"},{"type":"text","text":": 页面绘制"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"rIC: requestIdleCallback"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"window.requestIdleCallback()方法将在浏览器的空闲时段内调用的函数排队。这使开发者能够在主事件循环上执行后台和低优先级工作,而不会影响延迟关键事件,如动画和输入响应。函数一般会按先进先调用的顺序执行,然而,"},{"type":"text","marks":[{"type":"strong"}],"text":"如果回调函数指定了执行超时时间 timeout,则有可能为了在超时前执行函数而打乱执行顺序"},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"一个帧内要做这么多事情…… 如果 js 执行时间过长超过 16ms,就会 block 住,那么就会丢掉一次帧的绘制"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"宏任务的执行总在微任务之后,但是与其他的顺序不太确定"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"TIPS:协调的概念:比较虚拟 DOM 树,找出需要变更的节点,更新,称为协调(Reconcliation)"}]}]},{"type":"horizontalrule"},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"React16 之前的协调"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.geekbang.org\/infoq\/3d\/3d17cf1ad5aed65b8d140c517a424fee.gif","alt":"Image","title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"特点:"}]},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"递归调用,通过 React DOM 树级关系构成的栈递归"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在 virtualDOM 的比对过程中,发现一个 instance 有更新,会立即执行 DOM 操作。"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"同步更新,没发打断"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"代码示例"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"有下面这样一个 Component 组件,用他来模拟 DOM Diff 过程:"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"const Component = (\n  
\n    
\n      
\n      
\n    \n    
\n  \n)\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Diff 过程:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上面定义的 Component 组件会首先通过 Babel 转成 React.CreateElement 生成 ReactElement,也就是我们口中的虚拟 DOM(virtualDOM),如下类似 root 的结构(下面里面属性做了很多简化,只展示了结构)。"}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"let root = {\n  key: 'A1',\n  children: [\n    {\n      key: 'B1',\n      children: [\n        {\n          key: 'C1',\n          children: [],\n        },\n        {\n          key: 'C2',\n          children: [],\n        }\n      ],\n    },\n    {\n      key: 'B2',\n      children: [],\n    }\n  ],\n};\n\n\/\/ 深度优先遍历\nfunction walk(vdom) {\n  doWork(vdom);\n  vdom.children.forEach(child => {\n    walk(child);\n  })\n}\n\/\/ 更新操作\nfunction doWork(vdom) {\n  console.log(vdom.key);\n}\n\nwalk(root);\n"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"缺点:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"根据上面代码会发现,如果有大量更新或者有很深的组件结构树,执行 diff 操作的执行栈会越来越深并不能及时释放,那么 js 将一直占用主线程,一直要等到整棵 virtualDOM 树计算完成之后,才能把执行权交给渲染引擎,这就会导致用户的交互操作以及页面动画得不到响应,就会有明显感觉卡顿(掉帧),影响用户体验。"}]},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"解决:"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"把一个耗时长的任务分成很多小片,每一个小片的运行时间很短,虽然总时间依然很长,但是在每个小片执行完之后,都给其他任务一个执行的机会,这样唯一的线程就不会被独占,其他任务依然有运行的机会,所以 React 在 15 版本更新 16 版本时候推出了 Fiber 协调的概念。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"Fiber 概念"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"Fiber 是对 React 核心算法的重构,2 年重构的产物就是 Fiber Reconciler"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"核心目标:扩大其适用性,包括动画,布局和手势。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.geekbang.org\/infoq\/86\/86f7d72dc3063574382884db1be12836.gif","alt":"Image","title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"把可中断的工作拆分成小任务"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"对正在做的工作调整优先次序、重做、复用上次(做了一半的)成果"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在父子任务之间从容切换(yield back and forth),以支持 React 执行过程中的布局刷新"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"支持 "},{"type":"codeinline","content":[{"type":"text","text":"render()"}]},{"type":"text","text":" 返回多个元素"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"更好地支持 error boundary"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"每一个 Virtual DOM 节点内部都会生成对应的 Fiber。"}]}]},{"type":"horizontalrule"},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"Fiber 前置知识"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"怎么中断一个任务:实现一个类似于 Fiber 可中断的 workLoop。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"function sleep(delay) {\n  for (let start = Date.now(); Date.now() - start <= delay;) {}\n}\n\n\/\/ 每一个子项可以认为是一个 fiber\nconst works = [\n  () => {\n    console.log('第一个任务开始');\n    sleep(20);\n    console.log('第一个任务结束');\n  },\n  () => {\n    console.log('第 2 个任务开始');\n    sleep(20);\n    console.log('第 2 个任务结束');\n  },\n  () => {\n    console.log('第 3 个任务开始');\n    sleep(20);\n    console.log('第 3 个任务结束');\n  },\n];\n\nwindow.requestIdleCallback(workLoop, { timeout: 1000});\n\nfunction workLoop(deadLine) {\n  console.log('本帧的剩余时间剩', parseInt(deadLine.timeRemaining()));\n  \/*\n  * deadLine {\n  *   timeRemaining(), 返回此帧还剩下多少 ms 供用户使用\n  *   didTimeout 返回 cb 任务是否超时\n  * }\n  *\/\n  while ((deadLine.timeRemaining() > 0 || deadLine.didTimeout) && works.length > 0) { \/\/ 对象 两个属性 timeRemaining()\n    performUnitOfWord();\n  }\n\n  if (works.length > 0) {\n    window.requestIdleCallback(workLoop, { timeout: 1000});\n  }\n}\n\nfunction performUnitOfWord() {\n  works.shift()(); \/\/ 取出第一个元素执行\n}\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"单链表"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"存储数据的数据结构"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"数据以节点的形式表示,每个节点的构成:元素 + 指针(后续元素存储位置),元素就是存储数据的存储单元"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"单链表是 Fiber 中很重要的一个数据结构,很多异步更新逻辑都是通过单链表结构来实现的(setState 中的 UpdateQueue 更新链表也是基於单链表结构)"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"模拟一个类似 React 中 setState 批量更新的逻辑。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"\/**\n  Fiber 很多地方用到链表(单链表),尾指针没有指向\n *\/\n\nclass Update {\n  constructor(payload, nextUpdate) {\n    this.payload = payload;\n    this.nextUpdate = nextUpdate; \/\/ 下一个节点的指针\n  }\n}\n\nclass UpdateQueue {\n  constructor(payload) {\n    this.baseState = null; \/\/ 原状态\n    this.firstUpdate = null; \/\/ 第一次更新\n    this.lastUpdate = null; \/\/ 最后一次更新\n  }\n\n  enqueueUpdate(update) {\n    if (this.firstUpdate === null) {\n      this.firstUpdate = this.lastUpdate =update;\n    } else {\n      this.lastUpdate.nextUpdate = update;\n      this.lastUpdate = update;\n    }\n  }\n  \/\/ 获取老状态,遍历链表,进行更新\n  forceUpdate() {\n    let currentState = this.baseState || {}; \/\/ 初始状态\n    let currentUpdate = this.firstUpdate;\n    while (currentUpdate) {\n      let nextState = typeof currentUpdate.payload === 'function'\n                      ? currentUpdate.payload(currentState)\n                      : currentUpdate.payload;\n      currentState = {\n        ...currentState,\n        ...nextState,\n      }; \/\/ 使用当前更新得到最新的状态\n      currentUpdate = currentUpdate.nextUpdate; \/\/ 找下一个节点\n    }\n    this.firstUpdate = this.lastUpdate = null; \/\/ 更新结束清空链表\n    this.baseState = currentState;\n    return currentState;\n  }\n}\n\/\/ 链表可以中断和恢复\n\/\/ 每次 setState 都会通过一个链表保存起来,最后合并\n\/\/ enqueueUpdate 可以类比为 setState 操作\nlet queue = new UpdateQueue();\nqueue.enqueueUpdate(new Update({ name: '微医集团' }));\nqueue.enqueueUpdate(new Update({ number: 0 }));\nqueue.enqueueUpdate(new Update(state => ({ number: state.number + 1 })));\nqueue.enqueueUpdate(new Update(state => ({ number: state.number + 1 })));\nconsole.log(queue)\nqueue.forceUpdate();\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.geekbang.org\/infoq\/8c\/8c14862d6d7a2151eaea67f4c1251721.webp","alt":"Image","title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"思考:为什么 setState 在合成事件中会是异步去更新的? 解释:我们通过伪代码发现,每次的 setState 并没有对 UpdataQueue 中的 state 做任何更新,只是把每次需要更新的值(或函数),放到了 UpdataQueue 的链表上面,在执行 forceUpdate 的时候再做统一处理,处理完之后更新 state,所以没有执行 forceUpdate 之前,我们拿到的 state 都不是我们预期想要的 state。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"React 中的 Fiber"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":null,"normalizeStart":1},"content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"Fiber 的两个执行阶段"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"协调 Reconcile(render):对 virtualDOM 操作阶段,对应到新的调度算法中,就是通过 Diff Fiber Tree "},{"type":"text","marks":[{"type":"strong"}],"text":"找出要做的更新工作"},{"type":"text","text":","},{"type":"text","marks":[{"type":"strong"}],"text":"生成 Fiber 树"},{"type":"text","text":"。这是一个 js 计算过程,计算结果可以被缓存,计算过程可以被打断,也可以恢复执行。 所以,React 介绍 Fiber Reconciler 调度算法时,有提到新算法具有可拆分、可中断任务的新特性,就是因为这部分的工作是一个纯 js 计算过程,"},{"type":"text","marks":[{"type":"strong"}],"text":"所以是可以被缓存、被打断和恢复的"},{"type":"text","text":"。"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"提交更新 commit: 渲染阶段,拿到更新工作,提交更新并调用对应渲染模块(React-DOM)进行渲染。为了防止页面抖动,该 "},{"type":"text","marks":[{"type":"strong"}],"text":"过程是同步且不能被打断"},{"type":"text","text":"。"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":4,"align":null,"origin":null},"content":[{"type":"text","text":"React 中定义一个组件用来创建 Fiber。"}]}]}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"const Component = (\n  
\n    A1\n    
\n      B1\n      
C1\n      
C2\n    \n    
B2\n  \n)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":5,"normalizeStart":5},"content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":5,"align":null,"origin":null},"content":[{"type":"text","text":"上面定义的 Component 是一个组件,babel 解析时候会默认调用 React.createElement()方法,最终生成下面代码所示这样的 virtualDOM 结构并传给 ReactDOM.render()方法进行调度。"}]}]}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"{\n \"type\":\"div\",\n \"key\":null,\n \"ref\":null,\n \"props\": {\n \"id\":\"A1\",\n \"children\":[\n \"A1\",\n {\n \"type\":\"div\",\n \"key\":null,\n \"ref\":null,\n \"props\":{\n \"id\":\"B1\",\n \"children\":[\n \"B1\",\n {\n \"type\":\"div\",\n \"key\":null,\n \"ref\":null,\n \"props\":{\n \"id\":\"C1\",\n \"children\":\"C1\"\n },\n \"_owner\":null,\n \"_store\":{\n\n }\n },\n {\n \"type\":\"div\",\n \"key\":null,\n \"ref\":null,\n \"props\":{\n \"id\":\"C2\",\n \"children\":\"C2\"\n },\n \"_owner\":null,\n \"_store\":{\n\n }\n }\n ]\n },\n \"_owner\":null,\n \"_store\":{\n\n }\n },\n {\n \"type\":\"div\",\n \"key\":null,\n \"ref\":null,\n \"props\":{\n \"id\":\"B2\",\n \"children\":\"B2\"\n },\n \"_owner\":null,\n \"_store\":{\n\n }\n }\n ]\n },\n \"_owner\":null,\n \"_store\":{\n\n }\n}"}]},{"type":"numberedlist","attrs":{"start":"4","normalizeStart":"4"},"content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":4,"align":null,"origin":null},"content":[{"type":"text","text":"render 方法会接受 Virtual DOM,为每个 Virtual DOM 创建 Fiber(render 阶段),并且按照一定关系连接接起来。"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":5,"align":null,"origin":null},"content":[{"type":"text","text":"fiber 结构"}]}]}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"class FiberNode {\n constructor(tag, pendingProps, key, mode) {\n \/\/ 实例属性\n this.tag = tag; \/\/ 标记不同组件类型,如 classComponent,functionComponent\n this.key = key; \/\/ react 元素上的 key 就是 jsx 上写的那个 key,也就是最终 ReactElement 上的\n this.elementType = null; \/\/ createElement 的第一个参数,ReactElement 上的 type\n this.type = null; \/\/ 表示 fiber 的真实类型 ,elementType 基本一样\n this.stateNode = null; \/\/ 实例对象,比如 class 组件 new 完后就挂载在这个属性上面,如果是 RootFiber,那么它上面挂的是 FiberRoot\n\n \/\/ fiber\n this.return = null; \/\/ 父节点,指向上一个 fiber\n this.child = null; \/\/ 子节点,指向自身下面的第一个 fiber\n this.sibling = null; \/\/ 兄弟组件, 指向一个兄弟节点\n \n this.index = 0; \/\/ 一般如果没有兄弟节点的话是 0 当某个父节点下的子节点是数组类型的时候会给每个子节点一个 index,index 和 key 要一起做 diff\n\n this.ref = null; \/\/ reactElement 上的 ref 属性\n\n this.pendingProps = pendingProps; \/\/ 新的 props\n this.memoizedProps = null; \/\/ 旧的 props\n this.updateQueue = null; \/\/ fiber 上的更新队列 执行一次 setState 就会往这个属性上挂一个新的更新, 每条更新最终会形成一个链表结构,最后做批量更新\n this.memoizedState = null; \/\/ 对应 memoizedProps,上次渲染的 state,相当于当前的 state,理解成 prev 和 next 的关系\n\n this.mode = mode; \/\/ 表示当前组件下的子组件的渲染方式\n\n \/\/ effects\n\n this.effectTag = NoEffect; \/\/ 表示当前 fiber 要进行何种更新\n this.nextEffect = null; \/\/ 指向下个需要更新的 fiber\n \n this.firstEffect = null; \/\/ 指向所有子节点里,需要更新的 fiber 里的第一个\n this.lastEffect = null; \/\/ 指向所有子节点中需要更新的 fiber 的最后一个\n\n this.expirationTime = NoWork; \/\/ 过期时间,代表任务在未来的哪个时间点应该被完成\n this.childExpirationTime = NoWork; \/\/ child 过期时间\n\n this.alternate = null; \/\/ current 树和 workInprogress 树之间的相互引用\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Fiber 有很多属性,所有子节点 Fiber 的连接接是通过 child,return,siblint 链接起来,alternate 连接的是每一次更新的状态,用来对比每次状态更新以及缓存,我们使用节点的 id 来标识每个 Fiber 组件,转换为 Fiber 最终会生成如下图所示的结构,也是类似于 virtualDOM 结构的,构建的顺序是先 child => sibling => return,如果当前节点没有 child 了,这个节点就会完成。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.geekbang.org\/infoq\/a6\/a6183899dd7bce8164dcae86693fd215.png","alt":"Image","title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Fiber 树"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"收集依赖"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"收集依赖是在生成 Fiber 过程 (render 阶段) 中同时完成的,按照每个节点完成的顺序来构建链表,每个有了 Fiber 的组件通过自己的 nextEffect 指向下一个需要更新的组件,每一个父节点都有 firstEffect 和 lastEffect 来连接自己子节点的第一次更新和最后一次更新,最终会生成下图这样的更新链表。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.geekbang.org\/infoq\/d6\/d6b91dea4493813e632713d1d79877e2.webp","alt":"Image","title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"副作用链表(更新链表)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"提交更新 commit"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"全部节点创建完 Fiber 之后,会进入 commit 阶段,会从 root 的 fistEffect(所有节点的第一个副作用阶段)开始更新,然后找 firstEffect 的 nextEffect 节点,以此类推,一气呵成全部更新完,然后清空更新链表,完成此次更新,这个过程不可打断。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"总结"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"以上是 React 大概工作流程,主要以首次更新全部节点需要创建 Fiber 来讨论,后续会更新:基于 Fiber 的 diff、React 中合成事件、各种类型组件 (类组件,Function 组件)、hooks、事件优先级(expirationTime) 在内部如何调度相关。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"horizontalrule"},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"头图:Unsplash"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"作者:武晓慧"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"原文:https:\/\/mp.weixin.qq.com\/s\/63YJi2Y3tX8CFsXuJqT9dQ"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"原文:解析 React 性能利器 — Fiber"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"来源:微医大前端技术 - 微信公众号 [ID:wed_fed]"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"转载:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。"}]}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章