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

如何提取嵌套JSON的details数据作为props传递给自定义组件渲染

解决方案

核心错误原因

你遇到的两个问题本质都是JSON层级访问错误:

  1. employee/date等字段存放在数据的details二级对象下,不能直接从一级数据对象取值
  2. details是普通对象而非数组,不能直接使用map方法遍历,不需要嵌套map逻辑

具体修改步骤

1. 修正CompanyInfoList组件的props传递逻辑

遍历从CompListContext拿到的公司数据数组时,从details二级对象下读取对应字段传递给Results组件,示例代码:

// CompanyInfoList.js 内的遍历逻辑
{companyList.map(item => (
  <Results
    key={item._id}
    // 从details字段下取对应属性,加可选链和兜底值避免数据未加载时报错
    employee={item.details?.employee ?? ''}
    date={item.details?.date ?? ''}
    tax={item.details?.tax ?? ''}
    balance={item.details?.balance ?? ''}
    company={item.company ?? ''}
  />
))}

2. 修正CompSearch组件的搜索匹配逻辑

你测试数据的公司名称为TEST-ABC,需要使用包含匹配而非全等匹配,同时忽略大小写避免匹配失败,过滤逻辑参考:

const filteredCompanyList = companyList.filter(item => {
  // 空关键词返回全部数据
  if (!searchKey) return true
  return item.company.toLowerCase().includes(searchKey.toLowerCase())
})

3. (可选)如果需要遍历details所有键值对渲染

如果你后续需要动态渲染details下的所有字段,不需要嵌套map,先把对象转为键值对数组再遍历即可:

// 在Results组件内遍历details所有字段
{Object.entries(details).map(([key, value]) => (
  <div key={key}>{key}: {value}</div>
))}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 15:54:03