Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react中的fiber 和 React Fiber 架构 #14

Open
mbaxszy7 opened this issue Jun 22, 2020 · 0 comments
Open

react中的fiber 和 React Fiber 架构 #14

mbaxszy7 opened this issue Jun 22, 2020 · 0 comments
Labels

Comments

@mbaxszy7
Copy link
Owner

mbaxszy7 commented Jun 22, 2020

记录一下自己对react fiber 的理解

React element

React 的JXS语法最终会被编译为ReactReact.createElement:

class Demo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  render() {
    return <span>{this.state.count}</span>;
  }
}

// 编译后
class Demo {
...
  render() {
    return React.createElement("span", null, this.state.count);
  }
}

在render方法中的React.createElement 会把span转变为如下的数据结构:

{
  $$typeof: Symbol(react.element),
  type: 'span',
  key:null
  props: {
      children: 0
  }
}

React 用$$typeof标识了一个 React element, 而每个这样的element对应了一个fiber。

什么是fiber

  • 一个fiber就是一个对象结构,包含了一系列要完成的任务。
  • react 的每一个element都对应了一个fiber(一棵elements树就对应了一棵fiber节点树)。
  • 一个fiber不会在每次render中重新创建,相反,它是一个可以被操作改变的数据结构,保留了组件的状态和dom。所以操作在每个fiber上任务(更新,删除等)都可以映射到对应的element。

为什么要用fiber

上面提到用fiber就是要完成一系列的任务,这些任务具体可以概括为:

  • 暂停任务,并且可以稍后继续
  • 为不同的任务标记优先级
  • 重用之前完成的任务
  • 终止不再需要的任务

这一些列的工作运用在一整棵fiber树(Fiber上下文)上也最终体现了react 的Fiber架构。让React有了优先级调度(schedule)的能力。也让React能把reconciliation(计算哪一部分的element 树需要被更新,计算更新的这一步也被分为很多unit,防止阻塞主线程)和render(使用那些计算好的更新信息,把更新渲染到用户屏幕上)分开,使得reconciliation可以重用在不同的平台上(React Native 、React DOM)

一个fiber的结构

几个重要属性如下:

 {
    type: React.createElement 对应的type,表明这个fiber 节点对应的element
    tag: 表明fiber 的类型
    pendingProps: 已经是被更新的props,需要被运用到子组件或者dom 元素上
    key: 对应prop 上的key
    stateNode:  dom节点(HostComponent) / 类组件的实例 (ClassComponent) / fn() (FunctionComponent) 
    nextEffect:  指向下一个**effect list**中的节点 (effect list:一个workInProgress(finishedWork)的子树,是在render阶段 最终需要决定被执行更新 的产物,会在commit阶段被处理)
    effectTag:  当前fiber需要执行的副作用类型
    alternate:  用于构成**workInProgress**(从当前fiber树构建而来,反应了需要被更新渲染到用户屏幕的状态树)
    return: 指向父fiber节点
    sibling: 指向兄弟fiber节点
    child: 指向child fiber节点
  }

推荐一篇很棒的介绍React Fiber的文章 完全理解React Fiber

React Fiber Architecture
React源码揭秘1 架构设计与首屏渲染

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant