React根据Props值动态加载组件报错问题求助
动态加载React组件报错:Element type is invalid
我参考动态加载React组件的方案,构建了Base组件——它接收字符串参数,以此查找并实例化对应的子组件,目前仅实现了“Users”相关组件的演示逻辑。但页面加载时持续抛出错误:
Element 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.
我检查过组件导入逻辑,IDE未提示错误,但页面始终无法正常渲染。已创建可复现的示例工程,逻辑看似简单却找不到问题根源,寻求解决方案。
问题根源
你的Base.tsx中,动态导入组件时的写法与子组件的导出方式不匹配:
UserGrid和UserForm均使用默认导出(export default UserGrid),但你在componentMap中通过.then(module => module.UserGrid)尝试获取命名导出,导致最终拿到的组件值为undefined,React无法识别该类型。
修复方案
调整动态导入的逻辑,正确获取组件的默认导出:
- 修改
componentMap的定义,直接返回import()的结果(默认导出会包含在模块的default属性中):
const componentMap: Record<string, () => Promise<{ default: React.ComponentType<any> }>> = { Users: () => import('./UserGrid'), UserForm: () => import('./UserForm'), };
- 在加载组件时,从模块对象中取出
default属性作为目标组件:
useEffect(() => { const loadComponent = async () => { const module = await componentMap[componentName](); setLoadedComponent(module.default); }; loadComponent(); }, [componentName]);
验证效果
修改后,React能正确获取到组件的类/函数实例,即可解决“Element type is invalid”的报错,页面正常渲染目标组件。
内容的提问来源于stack exchange,提问作者user101289
相关产品推荐
相关产品推荐

