因此以下动态加载效果很好:
return React.lazy(() => import("./hotels/components/" + componentName));
以下不起作用:
const path = "./hotels/components/";
return React.lazy(() => import(path + componentName));
现在我认为这可能与缩小器有关,因为在它工作的情况下,“导入”在 vscode 中变成蓝色。如果它不起作用,“导入”会显示黄色。
此外,当我编译它不起作用的情况时,我会收到以下警告:
Critical dependency: the request of a dependency is an expression
有人遇到过这个问题吗?
我尝试了这个类似问题的所有内容:
以下解决了错误并消除了警告。只需嵌入变量即可。
return React.lazy(() => import(`${path + componentName}`));
在我使用 TypeScript 的情况下,我必须在 getComponent.ts 中执行单独的函数
src -> 实用程序 -> getComponent.ts
import React, { lazy } from 'react';
type Component = React.LazyExoticComponent<React.ComponentType<any>>;
const componentCache: Record<string, Component> = {};
/**
* Retrieves a component based on a relative path from the ./src/ directory.
*
* @param {string} path - Relative path from the ./src/ directory.
* @param {string} name - Component name.
*/
export default function getComponent(path: string, name: string): any {
if (!componentCache[name]) {
componentCache[name] = lazy(() => import(`../${path}`));
}
return componentCache[name];
}
我们可以这样使用它:
{tabs.map((el, index) => (
<Box key={index}>
<React.Suspense fallback={<>...</>}>
{React.createElement(
getComponent(el.componentSrc, el.componentName)
)}
</React.Suspense>
</Box>
))}
选项卡中的数据
export const importerTabs: any[] = [
{
componentName: 'FirstCompoent',
componentSrc: 'Pages/FirstPage/FirstCompoent',
},
{
componentName: 'SecondComponent',
componentSrc: 'Pages/SecondPage/SecondComponent',
}
];