本篇只是简单分析 Fiber。
Fiber 调度与更新函数调用栈:(react-conciler\src\ReactFiberWorkLoop.js)
fiber-call-stack.png
模拟Fiber工作流程
NodeJS环境下,运行该JS文件: node xxx.js 即可看到输出结果
- 定义对象
const a1 = {name: 'a1', child: null, sibling: null, return: null};
const b1 = {name: 'b1', child: null, sibling: null, return: null};
const b2 = {name: 'b2', child: null, sibling: null, return: null};
const b3 = {name: 'b3', child: null, sibling: null, return: null};
const c1 = {name: 'c1', child: null, sibling: null, return: null};
const c2 = {name: 'c2', child: null, sibling: null, return: null};
const d1 = {name: 'd1', child: null, sibling: null, return: null};
const d2 = {name: 'd2', child: null, sibling: null, return: null};
- 定义对象之间的关系
a1.child = b1;
b2.child = c1;
b3.child = c2;
c1.child = d1;
b1.sibling = b2;
b2.sibling = b3;
d1.sibling = d2;
b3.return = a1;
c1.return = b2;
c2.return = b3;
d2.return = c1;
- 给出对象之间的遍历顺序
/****************************************
*
* a1 <------------------
* | |
* b1 ----> b2 -------> b3 <--
* | | | |
* --- c1 <--- c2 ---
* | |
* d1 -> d2
*
* DFS(Deep First Search) 深度优先搜索
*
****************************************/
- 具体的工程流程如下:
let nextUnitOfWork = a1;
workLoop();
function workLoop() {
while(nextUnitOfWork !== null) {
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
}
}
function performUnitOfWork(workInProgress) {
// first work for child
let next = beginWork(workInProgress);
if (next === null) {
// then work for sibling
next = completeUnitOfWork(workInProgress);
}
return next;
}
function beginWork(workInProgress) {
console.log('[performUnitOfWork][beginWork] => ' + workInProgress.name);
return workInProgress.child;
}
function completeUnitOfWork(workInProgress) {
while(true) {
let sibling = workInProgress.sibling;
let ret = workInProgress.return;
completeWork(workInProgress);
if (sibling) {
return sibling;
} else if (ret) {
workInProgress = ret;
continue;
} else {
return null;
}
}
}
function completeWork(workInProgress) {
console.log('[completeUnitOfWork][completeWork] => ' + workInProgress.name + '\n');
return null;
}
纸画流程图(DFS for Fiber Workflow)
simulate-fiber-workflow.jpeg