React JS中Component无法渲染,报Element type is invalid错误如何解决?
Unhandled Runtime Error
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports
错误成因
- 核心错误:你将普通JSX值当做了React组件调用。
RenderPage变量的赋值结果是fetchComment存在时map方法返回的JSX数组,或是fetchComment不存在时的布尔值false,本质是普通对象类型,不符合React要求的组件必须是字符串、类或函数的规则,使用<RenderPage></RenderPage>的组件调用写法就会触发该报错。 - 额外隐含错误:代码中
map循环的key字段使用了未定义的变量i,运行时会抛出变量未定义异常;此外fetchComment没有在当前组件内声明(既不是props也不是内部状态),属于遗漏的定义问题。
修复方案
方案1:直接渲染JSX值(推荐,适配绝大多数场景)
不需要将RenderPage封装为组件,直接返回变量值即可,同时修复变量未定义问题:
function Test({session, fetchComment}) { // 补充map的索引参数赋值给i const RenderPage = fetchComment &&( fetchComment?.map((comment, i)=>{ return <LoadComment key={i} timestamp={comment.timestamp?.toDate()} comment={comment.comment} image={comment.image} user={comment.user} /> }) ) // 直接返回JSX值,不需要组件调用语法 return RenderPage }
方案2:封装为独立函数组件(适用于逻辑需要复用的场景)
如果确实需要将该部分逻辑封装为组件,将RenderPage改为函数类型即可:
function Test({session, fetchComment}) { // 改造成函数组件 const RenderPage = () => { return fetchComment?.map((comment, i)=>{ return <LoadComment key={i} timestamp={comment.timestamp?.toDate()} comment={comment.comment} image={comment.image} user={comment.user} /> }) || null } // 此时支持组件调用写法 return <RenderPage /> }
内容的提问来源于stack exchange,提问作者Jeevan
相关产品推荐
相关产品推荐

