[英]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.