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

从jsx到fiber树 #25

Open
shen1992 opened this issue Feb 10, 2023 · 0 comments
Open

从jsx到fiber树 #25

shen1992 opened this issue Feb 10, 2023 · 0 comments

Comments

@shen1992
Copy link
Owner

shen1992 commented Feb 10, 2023

目录

  • react的runtime
    • jsx实现
    • reactElement实现
  • fiber介绍

react的runtime

jsx实现

当我们写jsx代码

<div id='oDiv'>123</div>

经过babel转换后可得

import { jsx as _jsx } from 'react/js-runtime' 

_jsx('div', {
  children: '123',
  id: 'oDiv'
})

接下来继续看jsx的实现

export const jsx = (type, config) => {
  let key = null
  const props = {}
  let ref = null

  for (const prop in config) {
    const val = config[prop]
    if (prop === 'key') {
       key = '' + val
       continue
    }
    if (prop === 'ref') {
       if (val !== undefined) {
          ref = val
          continue
       }
   }
   if ({}.hasOwnProperty.call(config, prop)) {
       props[prop] = val
   }
  }
   return ReactElement(type, key, ref, props)
}

reactElement实现

比较简单,就直接上代码吧

const ReactElement = (type, key, ref, props) => {
    const element = {
        $$typeof: REACT_ELEMENT_TYPE,
        type,
	key,
	ref,
	props,
    }
    retrun element
}

可以看到reactElement返回一个对象,用对象可以很方便的描述一个dom,后续可以用它来创建fiber节点、进行diff比较,以上就是react的runtime。

fiber介绍

react的理念是构建快速响应的大型web应用,浏览器每16.6ms刷新一次,期间要执行js、样式布局、样式绘制,如果js执行时间过长,就没有时间进行样式布局和样式绘制了,用户就会直观的感觉到掉帧,卡顿。

为了解决这个问题,react实现了Concurrent Mode,浏览器有一个API叫做requestIdsCallback,它在浏览器闲置的时候执行callback,当然react为了兼容性,自己实现了一个类似的方法,为了方便理解,我们使用这个API做介绍就行。

react的render周期在requestIdsCallback回调中执行,期间如果有优先级更高的操作,比如用户输入,动画等,随时可以把控制权限交还给浏览器,所以render周期是可以被打断的。

为了实现这个能力,react需要构建fiber树,render周期被打断之后,当浏览器闲置下来,还可以继续从被打断的节点继续执行。

class FiberNode {
    construtor(tag, props, key) {
        // 构成树状结构
        this.return = null
        this.sibling = null
        this.child = null
    }
}
@shen1992 shen1992 changed the title 从jsx到fiber树 从jsx到fiber树(一) Feb 12, 2023
@shen1992 shen1992 changed the title 从jsx到fiber树(一) 从jsx到fiber树 Feb 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant