React在函数式组件中践行“代数效应”,用于将副作用从函数调用中分离。
React Fiber可以理解为:React内部实现的一套状态更新机制,支持任务不同优先级,可
中断与恢复,再恢复后可以服用之前的中间状态。

Fiber的含义

  1. 作为架构,之前的React15的Reconciler采用递归的方式执行,数据保存在递归调用栈中(stack Reconciler)。React16的Reconciler基于Fiber节点实现,被称为Fiber Reconciler。
  2. 作为静态的数据结构来说,每一个Fiber节点对应一个React element,保存该组件的类型(函数组件/类组件/原生组件…)对应的Dom节点等信息
  3. 作为动态的工作单元来说,每一个Fiber节点保存是本次更新该组件改变的状态,要执行的工作(需要被删除/被插入页面中/被更新…)

    Fiber结构

    Fiber节点的属性定义

    1. function FiberNode(
    2. tag: WorkTag,
    3. pendingProps: mixed,
    4. key: null | string,
    5. mode: TypeOfMode,
    6. ) {
    7. // 作为静态数据结构的属性
    8. this.tag = tag;
    9. this.key = key;
    10. this.elementType = null;
    11. this.type = null;
    12. this.stateNode = null;
    13. // 用于连接其他Fiber节点形成Fiber树
    14. // 指向父级Fiber节点
    15. this.return = null;
    16. // 指向子Fiber节点
    17. this.child = null;
    18. // 指向右边第一个兄弟Fiber节点
    19. this.sibling = null;
    20. //index对于多个Fiber节点,表示他们插入Fiber的位置
    21. this.index = 0;
    22. this.ref = null;
    23. // 作为动态的工作单元的属性
    24. this.pendingProps = pendingProps;
    25. this.memoizedProps = null;
    26. this.updateQueue = null;
    27. this.memoizedState = null;
    28. this.dependencies = null;
    29. this.mode = mode;
    30. this.effectTag = NoEffect;
    31. this.nextEffect = null;
    32. this.firstEffect = null;
    33. this.lastEffect = null;
    34. // 调度优先级相关
    35. this.lanes = NoLanes;
    36. this.childLanes = NoLanes;
    37. // 指向该fiber在另一次更新时对应的fiber
    38. this.alternate = null;
    39. }

    作为架构来说

    每一个Fiber节点有一个对应的React element,多个Fiber节点连接。

    1. 依靠return、child、sibling属性
    1. // 指向父级Fiber节点
    2. this.return = null;
    3. // 指向子Fiber节点
    4. this.child = null;
    5. // 指向右边第一个兄弟Fiber节点
    6. this.sibling = null;

    Fiber架构的实现原理 - 图1

    作为静态的数据结构,保存组件相关信息

    1. // Fiber对应组件的类型 Function/Class/Host...
    2. this.tag = tag;
    3. // key属性
    4. this.key = key;
    5. // 大部分情况同type,某些情况不同,比如FunctionComponent使用React.memo包裹
    6. this.elementType = null;
    7. // 对于 FunctionComponent,指函数本身,对于ClassComponent,指class,对于HostComponent,指DOM节点tagName
    8. this.type = null;
    9. // Fiber对应的真实DOM节点
    10. this.stateNode = null

    作为动态的工作单元

    ```html // 保存本次更新造成的状态改变相关信息 this.pendingProps = pendingProps; this.memoizedProps = null; this.updateQueue = null; this.memoizedState = null; this.dependencies = null;

this.mode = mode;

// 保存本次更新会造成的DOM操作 this.effectTag = NoEffect; this.nextEffect = null;

this.firstEffect = null; this.lastEffect = null;

  1. ```html
  2. // 调度优先级相关
  3. this.lanes = NoLanes;
  4. this.childLanes = NoLanes;