没有默认导出的 React.lazy (懒加载组件)

335 阅读1分钟

React v16.6.0 引入了 React.lazy,允许无需任何外部库进行代码分割。前往这里了解详情。

React.lazy 函数允许你将动态导入呈现为常规组件。来看如下一个示例:

在以前,我们只能如此导入组件:

import CommonComponent from "./CommonComponent";

const Component = () => {
  return (
    <div>
      <CommonComponent />
    </div>
  );
};

使用 React.lazy,我们可以像如下这样导入组件:

// 也可以直接导入
// import { lazy } from 'React'
const CommonComponent = React.lazy(() => import("./CommonComponent"));

const Component = () => {
  return (
    <div>
      <CommonComponent />
    </div>
  );
};

可以前往这里了解 lazy 用法。

React.lazy 接受一个必须调用动态 import() 的函数。这必须返回一个 Promise,该 Promise 解析为一个具有默认导出的模块,其中包含一个 React 组件。

这意味着你的 CommonComponent 应该以这种方式导出:

export default function CommonComponent() {
  return <div>CommonComponent</div>;
}

但是如果你没有将其作为默认导出该怎么办?

export function CommonComponent() {
  return <div>CommonComponent</div>;
}

在这种情况下,你必须在导入此组件时稍微更改 import() 代码。

const CommonComponent = React.lazy(() =>
  import("./CommonComponent").then((mod) => ({ default: mod.CommonComponent }))
);

我们在这里做的只是调用 import() 返回的 Promise 的 then 方法,在 then 方法当中处理默认导出,添加了一个 default 关键字。

请记住,使用 React.lazy 导入的组件应在 React.Suspense 中呈现。Suspense 组件接收一个 fallback 属性,这个属性用于设置组件懒加载时未呈现所展示的组件,通常是一个 Loading 组件。如以下一个示例:

const CommonComponent = React.lazy(() =>
  import("./CommonComponent").then((mod) => ({ default: mod.CommonComponent }))
);

const Loading = () => <div>组件加载中.....</div>;
const App = () => {
  return (
    <>
      <Suspense fallback={<Loading />}>
        <CommonComponent />
      </Suspense>
    </>
  );
};

前往这里查看详情。