React-源码阅读6037

55次阅读

共计 1989 个字符,预计需要花费 5 分钟才能阅读完成。

React 源码阅读 -6

lazy

React.lazy 函数能让你像渲染常规组件一样处理动态引入(的组件)。

React.lazy 接受一个函数,这个函数需要动态调用 import()。它必须返回一个 Promise,该 Promise 需要 resolve 一个 defalut exportReact 组件。

React.lazy 并不适合 SSR

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>): LazyComponent<T> {
  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'));

在组件首次渲染时,自动导入包含 OtherComponent 组件的包。

路由分割代码

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 = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/about" component={About}/>
      </Switch>
    </Suspense>
  </Router>
);

https://juejin.im/post/5c7d4a…
https://zh-hans.reactjs.org/d…

正文完
 0