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

React中Map渲染组件出现对象无效作为React子元素错误求助

React遍历数组渲染子组件时CompanyList2报错问题解决

问题概述

使用map遍历CompanyListItems数组渲染子组件时,CompanyList1可正常工作,但CompanyList2抛出以下错误:

Uncaught Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.

同时打印Score显示为undefined,移除CompanyList2中Name的渲染后错误消失,但所有props仍为undefined。

错误原因

React组件的props是以单一对象的形式传递给组件函数的,而CompanyList2的参数写法错误,将props拆分为多个独立参数接收:

// 错误写法:第一个参数是整个props对象,后续参数均为undefined
const CompanyList2 = (Avatar, Name, Score, Id) => { ... }

导致:

  • Avatar实际是包含所有props的完整对象,而非传入的头像地址
  • Name、Score、Id均为undefined
    渲染{Name}时,虽然undefined本身可被React渲染,但结合其他错误用法(如将props对象传给img的src属性)触发了对象不能作为React子元素的报错。

修复方案

通过对象解构正确接收props,有两种常用写法:

写法一:参数直接解构

const CompanyList2 = ({ Avatar, Name, Score, Id }) => {
  console.log(Score); // 现在能正确获取到值
  // ... 后续渲染代码
}

写法二:先接收props对象再解构

const CompanyList2 = (props) => {
  const { Avatar, Name, Score, Id } = props;
  console.log(Score); // 现在能正确获取到值
  // ... 后续渲染代码
}

另外,由于Score是空字符串,可添加默认值优化显示:

نمره روانشناس : {Score || '暂无评分'}

修复后的完整CompanyList2代码

const CompanyList2 = ({ Avatar, Name, Score, Id }) => {
  console.log(Score); // 现在能正确输出值
  return (
    <div className=" mt-6 mx-auto a-box relative col-span-3 md:col-span-1">
      <div className="img-container">
        <div className="img-inner">
          <div className="inner-skew">
            <img src={Avatar}/>
          </div>
        </div>
      </div>
      <div className="text-container">
        <h3>{Name}</h3>
        <div className='text-xs my-2 font-extrabold'>
          <FaRegStarHalf
            className='text-yellow-400 ml-2 text-xl inline-block' />
          نمره روانشناس : {Score || '暂无评分'}
        </div>
      </div>
      <Link to={`/Dashboard/${Id}/Company`}>
        <button className='text-xs
                           text-white
                           w-36
                           bg-yellow-500 absolute -bottom-3 left-12 p-3 rounded-2xl
                            hover:bg-yellow-600
                             transition-all
                             ease-in-out duration-300
                             hover:rounded-3xl'>
          رفتن به صحفه دکتر
        </button>
      </Link>
    </div>
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:50:26