Reactソース読解-6_037


Reactソース読解-6lazy React.lazy関数を使用すると、通常のコンポーネントをレンダリングするように動的に導入されたコンポーネントを処理できます.React.lazyは、import()を動的に呼び出す必要がある関数を受け入れる.Promiseを返さなければなりません.Promiseは、resolvedefalut exportコンポーネントを必要とします.React
import type {LazyComponent, Thenable} from 'shared/ReactLazyComponent';

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

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

  if (__DEV__) {
    // In production, this would just set it on the object.
    let defaultProps;
    let propTypes;
    Object.defineProperties(lazyType, {
      defaultProps: {
        configurable: true,
        get() {
          return defaultProps;
        },
        set(newDefaultProps) {
          warning(
            false,
            'React.lazy(...): It is not supported to assign `defaultProps` to ' +
              'a lazy component import. Either specify them where the component ' +
              'is defined, or create a wrapping component around it.',
          );
          defaultProps = newDefaultProps;
          // Match production behavior more closely:
          Object.defineProperty(lazyType, 'defaultProps', {
            enumerable: true,
          });
        },
      },
      propTypes: {
        configurable: true,
        get() {
          return propTypes;
        },
        set(newPropTypes) {
          warning(
            false,
            'React.lazy(...): It is not supported to assign `propTypes` to ' +
              'a lazy component import. Either specify them where the component ' +
              'is defined, or create a wrapping component around it.',
          );
          propTypes = newPropTypes;
          // Match production behavior more closely:
          Object.defineProperty(lazyType, 'propTypes', {
            enumerable: true,
          });
        },
      },
    });
  }

  return lazyType;
}

使用前
import OtherComponent from './OtherComponent';

使用後
const OtherComponent = React.lazy(() => import('./OtherComponent'));

コンポーネントが最初にレンダリングされると、React.lazy SSRコンポーネントを含むパッケージが自動的にインポートされます.
ルーティング分割コード
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';

const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));

const App = () => (
  
    Loading...
}>
);
https://juejin.im/post/5c7d4a...
https://zh-hans.reactjs.org/d...