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

React子组件接收对象数组Props时返回undefined的问题

问题排查与解决

核心问题:组件导出与导入名称不匹配

你遇到的cards为undefined的问题,根源在于子组件的导出名称和父组件的导入名称不一致:

  • 子组件定义的组件名为Children,但导出的是CardSpanCol2
  • 父组件导入的是Children,实际并没有正确引入你写的子组件逻辑,导致props无法正常传递

修复步骤

1. 统一组件名称(二选一即可)

方案一:修改子组件的导出语句

将子组件的最后一行:

export default CardSpanCol2;

改为:

export default Children;

方案二:修改父组件的导入与使用

父组件中,先修改导入语句:

import CardSpanCol2 from './Children'

然后修改组件调用:

<CardSpanCol2 cards={cards} />

2. 添加安全渲染逻辑(可选但推荐)

即使修复了名称问题,若cards数组为空或加载延迟,仍可能出现类似报错。可以通过可选链操作符或条件渲染避免:

const Children = ({ cards }) => {
  console.log({cards});

  return (
    <div className="bg-white w-full h-60 md:col-span-2 rounded-lg">
      {/* 使用可选链安全访问 */}
      {cards?.[0]?.title}
      {/* 或者用条件渲染显示默认内容 */}
      {/* {cards && cards.length > 0 ? cards[0].title : '暂无内容'} */}
    </div>
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:55:44