[英]How do you load React components asynchronously based on different server side states?
我希望能够基于不同的用户类型异步加载React组件。 例如,当用户A在应用程序中导航时,它们的组件集将通过异步加载。 然后,当用户B使用该应用程序时,他们收到了一组同样通过异步加载的组件。
目前,我正在使用React Router和Redux。 我还使用Webpack来创建组件块,这些组件将异步加载,如下所示:
<Route
path="/"
getComponent={(location, callback) => {
require.ensure([], (require) => {
callback(null, require('./app/App.jsx').default);
}, 'App');
}}
>
但是,当我尝试扩展它以动态加载组件时,它不起作用。 我创建了一个对象数组,其中包含我要加载的所有组件...
{
components: [
{
id: 0,
name: 'Dashboard',
src: './dashboard/Dashboard.jsx',
indexRoute: true,
path: '/',
},
{
id: 1,
name: 'Quote',
src: './quote/Quote.jsx',
indexRoute: false,
path: '/quote',
},
],
}
然后,我使用map为这些组件中的每个组件创建路线。
const routes = components.map((component) => {
if (component.indexRoute) {
return (
<IndexRoute
getComponent={(location, callback) => {
require.ensure([], (require) => {
callback(null, require(component.src).default);
}, component.name);
}}
key={component.id}
/>
);
}
return (
<Route
path={component.path}
getComponent={(location, callback) => {
require.ensure([], (require) => {
callback(null, require(component.src).default);
}, component.name);
}}
key={component.id}
/>
);
});
但是当我将创建的路线插入主路线时...
<Route
path="/"
getComponent={(location, callback) => {
require.ensure([], (require) => {
callback(null, require('./app/App.jsx').default);
}, 'App');
}}
>
{routes}
</Route>
我收到以下错误:
Uncaught TypeError: __webpack_require__(...).ensure is not a function
和警告:
require function is used in a way in which dependencies cannot be statically extracted
我认为这是因为Webpack需要知道在构建时必须编译哪些块? 这是问题吗,有办法解决吗? 甚至更好的解决方案?
谢谢
对于以后遇到此问题的任何人,我都设法通过创建一个包含我的应用程序可能会加载的所有异步组件的对象来解决此问题。 每个组件路由定义都有它的require.ensure函数,定义如下:
const asyncComponents = [
{
id: 0,
name: 'Dashboard',
require: (location, callback) => {
require.ensure([], (require) => {
callback(null, require('./dashboard/Dashboard.jsx').default);
}, 'Dashboard');
},
},
];
export default asyncComponents;
这样做将不可避免地会在某些时候遇到扩展问题,因为您必须维护所有组件的单独列表。 它现在可以使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.