Skip to content

警告: React.createElement: 类型是 无效 -- expected 字符串 or 函数/组件但 获取: undefined

错误信息

                元素类型是 无效: expected 字符串 or 函数/组件但 获取: undefined.
              

快速摘要

你 rendered `<SomeComponent />` 但 `SomeComponent` 是 undefined, 经常 due 到默认/named 导出 mismatch.

为什么发生

  • Imported named 导出 as 默认 or vice versa

  • 组件 file doesn't 导出任何事

  • Circular 导入 issue

  • 动态导入 returned undefined

最小示例

✗ 错误代码
// Component uses named export
export function Header() { return <h1>Hi</h1>; }

// But imported as default
import Header from "./Header"; // undefined!
✓ 修复代码
// Use named import
import { Header } from "./Header";

file uses named 导出但 导入 uses 默认语法, resulting in undefined. Matching 导入到 导出 fixes 它.

如何诊断

  • 检查导入语句 and 导出 in 组件 file

  • Log 组件之前渲染: console.log(SomeComponent)

  • 验证导出类型 (默认对比 named) matches 导入

如何修复

  • Fix 导入到 match 导出: 导入 { 组件 } for named, 导入组件 for 默认

  • Ensure 组件 file 有正确导出语句

  • Resolve circular 导入通过 restructuring dependencies

如何预防

  • 是 consistent 使用默认对比 named 导出

  • Use IDE auto-导入到 avoid mismatches

相关资源

相关术语

相关课程

  • 组件

    学习组件导入 and 导出.

← 返回语言