首页 > 其他分享 >React性能优化的8种方式

React性能优化的8种方式

时间:2022-11-08 12:56:56浏览次数:65  
标签:function fiber const 性能 React export wip null 优化

一 引沿

Fiber 架构是React16中引入的新概念,目的就是解决大型 React 应用卡顿,React在遍历更新每一个节点的时候都不是用的真实DOM,都是采用虚拟DOM,所以可以理解成fiber就是React的虚拟DOM,更新Fiber的过程叫做调和,每一个fiber都可以作为一个执行单元来处理,所以每一个 fiber 可以根据自身的过期时间expirationTime,来判断是否还有空间时间执行更新,如果没有时间更新,就要把主动权交给浏览器去渲染,做一些动画,重排( reflow ),重绘 repaints 之类的事情,这样就能给用户感觉不是很卡。

二 什么是调和

调和是一种算法,就是React对比新老虚拟DOM的过程,以决定需要更新哪一部分。

三 什么是Filber

Fiber的目的是为了让React充分利用调度,以便做到如下几点:

  • 暂停工作,稍后再回来
  • 优先考虑不同类型的工作
  • 重用以前完成的工作
  • 如果不再需要,则中止工作

为了实现上面的要求,我们需要把任务拆分成一个个可执行的单元,这些可执行的单元就叫做一个Fiber,一个Fiber就代表一个可执行的单元。

一个Fiber就是一个普通的JS对象,包含一些组件的相关信息。

function FiberNode(){
  this.tag = tag;                  // fiber 标签 证明是什么类型fiber。
  this.key = key;                  // key调和子节点时候用到。 
  this.type = null;                // dom元素是对应的元素类型,比如div,组件指向组件对应的类或者函数。  
  this.stateNode = null;           // 指向对应的真实dom元素,类组件指向组件实例,可以被ref获取。

  this.return = null;              // 指向父级fiber
  this.child = null;               // 指向子级fiber
  this.sibling = null;             // 指向兄弟fiber 
  this.index = 0;                  // 索引

  this.ref = null;                 // ref指向,ref函数,或者ref对象。

  this.pendingProps = pendingProps;// 在一次更新中,代表element创建
  this.memoizedProps = null;       // 记录上一次更新完毕后的props
  this.updateQueue = null;         // 类组件存放setState更新队列,函数组件存放
  this.memoizedState = null;       // 类组件保存state信息,函数组件保存hooks信息,dom元素为null
  this.dependencies = null;        // context或是时间的依赖项

  this.mode = mode;                //描述fiber树的模式,比如 ConcurrentMode 模式

  this.effectTag = NoEffect;       // effect标签,用于收集effectList
  this.nextEffect = null;          // 指向下一个effect

  this.firstEffect = null;         // 第一个effect
  this.lastEffect = null;          // 最后一个effect

  this.expirationTime = NoWork;    // 通过不同过期时间,判断任务是否过期, 在v17版本用lane表示。

  this.alternate = null;           //双缓存树,指向缓存的fiber。更新阶段,两颗树互相交替。
}

type 就是react的元素类型

export const FunctionComponent = 0;       // 对应函数组件
export const ClassComponent = 1;          // 对应的类组件
export const IndeterminateComponent = 2;  // 初始化的时候不知道是函数组件还是类组件 
export const HostRoot = 3;                // Root Fiber 可以理解为跟元素 , 通过reactDom.render()产生的根元素
export const HostPortal = 4;              // 对应  ReactDOM.createPortal 产生的 Portal 
export const HostComponent = 5;           // dom 元素 比如 <div>
export const HostText = 6;                // 文本节点
export const Fragment = 7;                // 对应 <React.Fragment> 
export const Mode = 8;                    // 对应 <React.StrictMode>   
export const ContextConsumer = 9;         // 对应 <Context.Consumer>
export const ContextProvider = 10;        // 对应 <Context.Provider>
export const ForwardRef = 11;             // 对应 React.ForwardRef
export const Profiler = 12;               // 对应 <Profiler/ >
export const SuspenseComponent = 13;      // 对应 <Suspense>
export const MemoComponent = 14;          // 对应 React.memo 返回的组件

比如元素结构如下:

export default class Parent extends React.Component{
   render(){
     return <div>
       <h1>hello,world</h1>
       <Child />
     </div>
   }
}

function Child() {
  return <p>child</p>
}

对应的Filber结构如下:

alt 属性文本

有了上面的概念后我们就自己实现一个Fiber的更新机制

四 实现调和的过程

我们通过渲染一段jsx来说明React的调和过程,也就是我们要手写实现ReactDOM.render()

const jsx = (
  <div className="border">
    <h1>hello</h1>
    <a href="https://www.reactjs.org/">React</a>
  </div>
)

ReactDOM.render(
  jsx,
  document.getElementById('root')
);

1. 创建FiberRoot

react-dom.js

function createFiberRoot(element, container){
    return {
    type: container.nodeName.toLocaleLowerCase(),
    props: { children: element },
    stateNode: container
  }
}


function render(element, container) {
  const FibreRoot = createFiberRoot(element, container)
  scheduleUpdateOnFiber(FibreRoot)
}
export default { render }

参考React实战视频讲解:进入学习

2. render阶段

调和的核心是render和commit,本文不讲调度过程,我们会简单的用requestIdleCallback代替React的调度过程。

ReactFiberWorkloop.js

let wipRoot = null // work in progress
let nextUnitOfwork = null // 下一个fiber节点

export function scheduleUpdateOnFiber(fiber) {
  wipRoot = fiber
  nextUnitOfwork = fiber
}

function workLoop(IdleDeadline) {
  while(nextUnitOfwork && IdleDeadline.timeRemaining() > 0) {
    nextUnitOfwork = performUnitOfWork(nextUnitOfwork)
  }
}

function performUnitOfWork() {}

requestIdleCallback(workLoop)

每一个 fiber 可以看作一个执行的单元,在调和过程中,每一个发生更新的 fiber 都会作为一次 workInProgress 。那么 workLoop 就是执行每一个单元的调度器,如果渲染没有被中断,那么 workLoop 会遍历一遍 fiber 树

performUnitOfWork 包括两个阶段:

  1. 是向下调和的过程,就是由 fiberRoot 按照 child 指针逐层向下调和,期间会执行函数组件,实例类组件,diff 调和子节点
  2. 是向上归并的过程,如果有兄弟节点,会返回 sibling兄弟,没有返回 return 父级,一直返回到 fiebrRoot

这么一上一下,构成了整个 fiber 树的调和。

import { updateHostComponent } from './ReactFiberReconciler'
function performUnitOfWork(wip) {
  // 1. 更新wip
  const { type } = wip
  if (isStr(type)) {
    // type是string,更新普通元素节点
    updateHostComponent(wip)
  } else if (isFn(type)) {
    // ...
  }

  // 2. 返回下一个要更新的任务 深度优先遍历
  if (wip.child) {
    return wip.child
  }
  let next = wip
  while(next) {
    if (next.sibling) {
      return next.sibling
    }
    next = next.return
  }
  return null
}

根据type类型区分是FunctionComponent/ClassComponent/HostComponent/...
本文中只处理HostComponent类型,其他类型的处理可以看文末的完整代码链接。

ReactFiberReconciler.js

import { createFiber } from './createFiber'

export function updateHostComponent(wip) {
  if (!wip.stateNode) {
    wip.stateNode = document.createElement(wip.type);
    updateNode(wip.stateNode, wip.props);
  }
  // 调和子节点
  reconcileChildren(wip, wip.props.children);
}

function reconcileChildren(returnFiber, children) {
  if (isStr(children)) {
    return
  }

  const newChildren = isArray(children) ? children : [children];
  let previousNewFiber = null
  for(let i = 0; i < newChildren.length; i++) {
    const newChild = newChildren[i];
    const newFiber = createFiber(newChild, returnFiber)

    if (previousNewFiber === null) {
      returnFiber.child = newFiber
    } else {
      previousNewFiber.sibling = newFiber
    }
    previousNewFiber = newFiber
  }
}

function updateNode(node, nextVal) {
  Object.keys(nextVal).forEach((k) => {
    if (k === "children") {
      if (isStringOrNumber(nextVal[k])) {
        node.textContent = nextVal[k];
      }
    } else {
      node[k] = nextVal[k];
    }
  });
}

createFiber.js

export function createFiber(vnode, returnFiber) {
  const newFiber = {
    type: vnode.type,   // 标记节点类型
    key: vnode.key,     // 标记节点在当前层级下的唯一性
    props: vnode.props, // 属性
    stateNode: null,    // 如果组件是原生标签则是dom节点,如果是类组件则是类实例
    child: null,        // 第一个子节点
    return: returnFiber,// 父节点
    sibling: null,      // 下一个兄弟节点
  };

  return newFiber;
}

至此已经完成了render阶段,下面是commit阶段,commit阶段就是依据Fiber结构操作DOM

function workLoop(IdleDeadline) {
  while(nextUnitOfwork && IdleDeadline.timeRemaining() > 0) {
    nextUnitOfwork = performUnitOfWork(nextUnitOfwork)
  }

  // commit
  if (!nextUnitOfwork && wipRoot) {
    commitRoot();
  }
}

function commitRoot() {
  commitWorker(wipRoot.child)
  wipRoot = null;
}

function commitWorker(wip) {
  if (!wip) {
    return
  }
  // 1. 提交自己
  const { stateNode } = wip
  let parentNode = wip.return.stateNode
  if (stateNode) {
    parentNode.appendChild(stateNode);
  }

  // 2. 提交子节点
  commitWorker(wip.child);

  // 3. 提交兄弟节点
  commitWorker(wip.sibling);
}

五 总结

  • Fiber结构,Fiber的生成过程。
  • 调和过程,以及 render 和 commit 两大阶段。

标签:function,fiber,const,性能,React,export,wip,null,优化
From: https://www.cnblogs.com/xiaofeng123aa/p/16869297.html

相关文章

  • 《高性能MySQL》第一章:MySQL架构与历史 读书笔记
    Chapter.1StructureandHistoryofMySQL1.1MySQLlogicalstructureMySQL逻辑架构如上图所示。最上层服务并非mysql独有,大部分基于网络的工具都有类似的C/S架构。第......
  • 界面组件Kendo UI for React R3 2022新版,让Web应用更酷炫
    KendoUI致力于新的开发,来满足不断变化的需求,通过React框架的KendoUIJavaScript封装来支持ReactJavascript框架。KendoUIforReact能够为客户提供更好的用户体验,并且......
  • React组件设计模式-纯组件,函数组件,高阶组件
    一、组件(1)函数组件如果你想写的组件只包含一个render方法,并且不包含state,那么使用函数组件就会更简单。我们不需要定义一个继承于React.Component的类,我们可以定......
  • ​给前端开发者的 14 个 JavaScript 代码优化建议
    英文|https://blog.bitsrc.io/14-javascript-code-optimization-tips-for-front-end-developers-a44763d3a0da作者| MahdhiRezvi译文| https://github.com/xitu/gold......
  • 基于 React 和 Redux 的 API 集成解决方案
    在前端开发的过程中,我们可能会花不少的时间去集成API、与API联调、或者解决API变动带来的问题。如果你也希望减轻这部分负担,提高团队的开发效率,那么这篇文章一定会对你......
  • 10个值得你去试试的React开发工具
    JavaScript每天都在出现大量的框架和工具,而React是除了上次我们提到的Vue和Ember之外另一款比较流行的框架。但因为新的工具每天都在不断的出现,开发者在尝试时总会有些不知......
  • 7种在React中使用CSS的方式
    第一种:在组件中直接使用style不需要组件从外部约会css文件,直接在组件中书写。importreact,{Component}from"react";constdiv1={width:"300px",margin:"30px......
  • React的5种高级模式
    本文概述了5种现代高级React模式,包括集成代码、优点和缺点,以及在公共库中的具体用法。像每个React开发者一样,你可能已经问过自己以下问题之一我如何建立一个可重复使用......
  • 性能优化的方法(上)
    引言:取与舍软件设计开发某种意义上是“取”与“舍”的艺术。关于性能方面,就像建筑设计成抗震9度需要额外的成本一样,高性能软件系统也意味着更高的实现成本,有时候与其他质......
  • 07_查询数据_查询性能_查询计划
    一、查询性能  代码:showgp_dynamic_partiton_pruning;  二、查询分析 1、查询计划  注:获取磁盘页的数量越少,I/O和CPU消耗的越少;     EXPLAIN......