您可以解构延迟加载的React组件吗?

时间:2019-11-10 18:20:24

标签: reactjs es6-module-loader react-suspense

使用es6导入,您可以执行以下操作:

import { MyComponent } from "../path/to/components.js";

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

我也可以用React.lazy吗?

const { MyComponent } = lazy(() => import("../path/to/components.js"));

我收到以下错误,但是我不确定这是否与这个错误或其他一些错误有关:

  

元素类型无效:应使用字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义

5 个答案:

答案 0 :(得分:6)

当我遇到 FontAwesome 的问题时,我是这样做的:

const FontAwesomeIcon = React.lazy(()=> import('@fortawesome/react-fontawesome').then(module=>({default:module.FontAwesomeIcon})))

答案 1 :(得分:4)

如果您使用 react-lazily,则可以。

import { lazily } from 'react-lazily';
const { MyComponent } = lazily(() => import("../path/to/components.js"));

它还允许导入多个组件:

const { MyComponent, MyOtherComponent, SomeOtherComponent } = lazily(
  () => import("../path/to/components.js")
);

有关更多选项,请参阅 this answer

答案 2 :(得分:1)

您不能使用React.lazy:

  

React.lazy采用必须调用动态import()的函数。这必须返回一个Promise,该Promise解析为一个带有默认导出的模块,该模块包含一个React组件。   (请参阅https://reactjs.org/docs/code-splitting.html#reactlazy

存在一种解决方法:创建一个中间模块,该模块导入您的命名导出并将其导出为默认值(参见https://reactjs.org/docs/code-splitting.html#named-exports

答案 3 :(得分:1)

我想要另一个解决方法。此组件链接了Promise,并将命名的导出添加到默认导出。 src。虽然,我不确定这是否会打破树的震动。 explanation here有点。

import {lazy} from 'react'
export default (resolver, name = 'default') => {
  return lazy(async () => {
    const resolved = await resolver()
    return {default: resolved[name]}
  })
}

答案 4 :(得分:1)

React.lazy当前仅支持默认导出。如果要导入的模块使用命名的导出,则可以创建一个中间模块,将其重新导出为默认模块。这样可以确保摇晃树一直有效,并且不会拉入未使用的组件。

// ManyComponents.js
export const MyComponent = /* ... */;
export const MyUnusedComponent = /* ... */;
// MyComponent.js
export { MyComponent as default } from "./ManyComponents.js";
// MyApp.js
import React, { lazy } from 'react';
const MyComponent = lazy(() => import("./MyComponent.js"));

更多信息: https://reactjs.org/docs/code-splitting.html#named-exports

相关问题