React 深度学习:ReactLazy

584 阅读1分钟

path:packages/react/src/ReactLazy.js

源码

import type {LazyComponent, Thenable} from 'shared/ReactLazyComponent';

import {REACT_LAZY_TYPE} from 'shared/ReactSymbols';
import warning from 'shared/warning';

export function lazy<T, R>(ctor: () => Thenable<T, R>): ø<T> {
  let lazyType = {
    ?typeof: REACT_LAZY_TYPE,
    _ctor: ctor,
    // React uses these fields to store the result.
    _status: -1,
    _result: null,
  };

  if (__DEV__) {
   // do something
  }

  return lazyType;
}

lazy 方法接收一个函数作为其方法,函数需要返回一个 Thenable 类型的值。

Thenable 是一个具有 then 方法的一个对象。在实际应用中,这个 Thenable 对应的就是 Promise 实例。

lazy 最后会返回一个 ?typeof 属性为 REACT_LAZY_TYPELazyComponent 对象。

LazyComponent 如何被解析

未完待续...

ReactLazyComponent

path: packages/shared/ReactLazyComponent.js

export type Thenable<T, R> = {
  then(resolve: (T) => mixed, reject: (mixed) => mixed): R,
};

export type LazyComponent<T> = {
  ?typeof: Symbol | number,
  _ctor: () => Thenable<{default: T}, mixed>,
  _status: 0 | 1 | 2,
  _result: any,
};

type ResolvedLazyComponent<T> = {
  ?typeof: Symbol | number,
  _ctor: () => Thenable<{default: T}, mixed>,
  _status: 1,
  _result: any,
};

export const Pending = 0;
export const Resolved = 1;
export const Rejected = 2;

export function refineResolvedLazyComponent<T>(
  lazyComponent: LazyComponent<T>,
): ResolvedLazyComponent<T> | null {
  return lazyComponent._status === Resolved ? lazyComponent._result : null;
}