我在应用程序中使用'react-loadable'来延迟加载一些我不希望在应用程序加载后立即呈现的组件,目前我正在执行基于路由的代码拆分。
我的文件结构:
ignitus-About/Components/index.js
的内容如下:
export { default as About } from './About';
这是我的延迟加载AboutUs组件的代码段:
const AboutUs = Loadable({
loader: () => import('../ignitus-About/Components/About'),
loading: Loading,
});
但是您将在这里注意到的是,我正在编写About组件的精确/完整路径,但是在我的Components
目录中,我只有2个文件,一个index.js
和另一个About.js
。
此处index.js
通过执行以下操作导出关于组件:
export { default as About } from './About';
但是当在我的可加载组件中时,我这样写:
const AboutUs = Loadable({
loader: () => import('../ignitus-About/Components'),
loading: Loading,
});
它抛出一个错误,所以我的问题是,react-lodable是否期望该组件的确切路径,否则我该如何从Loadable组件中的index.js
导出About组件。
因此,当我像这样延迟加载组件时:
const AboutUs = Loadable({
loader: () => import('../ignitus-About/Components/About'),
loading: Loading,
});
它工作正常。
如果我尝试像这样延迟加载:
const AboutUs = Loadable({
loader: () => import('../ignitus-About/Components'),
loading: Loading,
});
它会引发错误:
index.js:1452 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `LoadableComponent`.
in LoadableComponent (created by Route)
in Route (at publicRoutes.js:56)
in Switch (at publicRoutes.js:41)
in div (at publicRoutes.js:39)
in PublicRoutes (created by Route)
in Route (at App.js:36)
in Switch (at App.js:34)
in div (at App.js:25)
in App (at src/index.js:29)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.js:28)
in Provider (at src/index.js:27)
答案 0 :(得分:0)
问题是您的export { default as About } from './About';
语句。您没有导出默认值,因此当您在此处使用语句时,不会看到默认值:
loader: () => import('../ignitus-About/Components'),
当可加载组件尝试导入您的组件并使用react对其进行初始化时,它会尝试从默认导出../ignitus-About/Components
开始。这不存在。加载程序应该如何得知您想要About
,而不是从此导入中说出Blog
组件?
无论您要导入的导入内容是什么,它都必须是单个组件。如果您有多个组件,则需要使用多个react-loadable。