react源码解析 1 基础

864 阅读2分钟

本文是看视频后进行的技术总结笔记,原视频技术总结文档直接点击 React源码解析文档参考- https://react.jokcy.me/

react16

  • react16的更新完全重写核心代码,升级不用调兼容
  • 引入fiber,从根本上解决js单线程运行如果计算量太大导致的动画卡帧和交互卡顿的问题

内容设计

  1. react简单api
  2. react更新创建 update
  3. fiber Scheduler 调度器
  4. 各种不同的组件如何更新
  5. 完成各个节点更新的操作
  6. 提交更新
  7. context、ref、hydrate、事件体系的实现
  8. Suspense
  9. hooks

React 原理最核心部分

  • 更新机制
  • 什么是 Fiber 以及作用
  • React 实现路更新任务的调度 和如何实现的

React 的调度过程

React 的调度过程
React 渲染更新的过程
渲染更新的过程

基础

React Api

下面是 react暴露出来的api
React 顶层 API 官方文档链接

const React = {
    Children: {
        map,
        forEach,
        toarray,
        only,
    },
    
    createRef,
    Component,
    PureComponent,
    
    createContext,
    forwardRef,
    
    
    Fragment: REACT_FREGMENT_TYPE,
    StrictMode: REACT_STRICT_TYPE,
    unstable_AsyncMode: REACT_ASYNC_MODE_TYPE,
    unstable_Profiler: REACT_PROFILER_TYPE,
    
    createElemnt: _DEV_ ? createElmentWithValidation : createElment,
    cloneElemnt:  _DEV_ ? cloneElmentWithValidation : cloneElment,
    createFactory:  _DEV_ ? createFactoryWithValidation : createFactory,
    isValidElemnt:  isValidElemnt,
    
    version: ReactVersion,
    
    __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactSharedInternals,
}

ReactElement

ReactElement 通过 createElement创建 调用该方法需要传入的三个参数:

  • type
  • config
  • children

type是指 reactELement的类型

  • 字符串 比如 div p 代表原生DOM,称为 HostComponent
  • 继承自Component或者PureComponent 被称为ClassComponent
  • function Componennt
  • 原生提供的Fragment,AsyncMode等Symbol,会被特殊处理
  • TODO:是否有其他类型

点击 打开下文代码片段在线编译

export function createElement(type, config, children) {
  // 处理参数
  return ReactElement(
    type,
    key,
    ref,
    self,
    source,
    ReactCurrentOwner.current,
    props
  );
}
const ReactElement = function(type, key, ref, self, source, owner, props) {
  const element = {
    // This tag allows us to uniquely indentify this as React elemnt
    ?typeof: REACT_ELEMENT_TYPE,

    // Built-in properties that belong on the element
    type: type,
    key: key,
    ref: ref,
    props: props,

    // Record the component responsible for crateing elment
    _owner: owner
  };

  return element;
};

React Children

点击 打开下文代码片段在线编译

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class IgnoreFirstChild extends React.Component {
  render() {
    const children = this.props.children
    return (
      <div>
        <div>IgnoreFirstChild 组件</div>
        {React.Children.map(children, (child, i) => {
          // Ignore the first child
          if (i < 1) return
          return child
        })}
      </div>
    )
  }
}

ReactDOM.render(
  <div>
    <IgnoreFirstChild >
      <div>first child</div>
      <div>second child</div>
      <div>third child</div>
    </IgnoreFirstChild >
  </div>,
  document.getElementById('container'),
);

效果图:

效果图