You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React使用map函数动态渲染组件失败,求助排查错误

React map渲染组件报错:Element type is invalid: expected a string or a class/function but got: object

错误原因

  1. 你直接使用了<Joke/>组件,但从未定义过这个Joke组件——map回调里的参数名Joke是数组中的单个对象,你把它当成组件调用,React自然无法识别,因此抛出类型无效的错误。
  2. map遍历生成组件时未添加key属性,这是React列表渲染的强制要求,会导致额外渲染警告。

修复后的完整代码

import React from "react";
import "./index.css"
import ReactDOM from "react-dom/client";

// 先定义Joke函数组件
function Joke({ setup, punchline }) {
  return (
    <div className="joke-item">
      <p>{setup}</p>
      <p>{punchline}</p>
    </div>
  );
}

function App() {
  
  const array  = [
        {
            setup:"c'est un setup",
            punchline:"c'est une punchline"
        },
        {
            setup:"c'est un setup",
            punchline:"c'est une punchline"
        },
        {
            setup:"c'est un setup",
            punchline:"c'est une punchline"
        },
        {
            setup:"c'est un setup",
            punchline:"c'est une punchline"
        },
    ]

// 修改map参数名避免和组件名冲突,同时添加key属性
const jokeElements = array.map((item, index) => {
    return(
        <Joke 
          key={index} 
          setup={item.setup} 
          punchline={item.punchline}
        />
    )
})

return(
    <div>
      {jokeElements}
    </div>
)
}

let root = ReactDOM.createRoot(document.querySelector("#root"));
root.render(<App/>);

额外说明

  • 定义Joke组件后,React才能识别它是合法的函数组件,从而正常渲染。
  • 将map参数名从Joke改为item,避免变量名冲突导致的逻辑混淆。
  • key属性这里临时使用了数组索引,若你的数组对象有唯一标识(比如id字段),建议替换为key={item.id},这是React推荐的最佳实践。

内容的提问来源于stack exchange,提问作者william jaulin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 03:54:29