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

React中如何map访问JSON的Display objects并打印所有url列表

问题排查
  • 核心错误是item.content.attachments为数组类型,并非单个对象,无法直接通过.url访问属性,必须遍历该数组才能获取到每个元素的url字段。
正确实现方案

如果需要在每个新闻条目下展示其对应所有附件的url,可参考以下代码:

return pressReleases ? (
  <Main>
    {pressReleases.map((item) => (
      <TextCell key={item.news_id}>
        <CategoryText>
          {item.content.attachments?.map((attachment, index) => (
            <p key={index}>{attachment.url}</p>
          ))}
        </CategoryText>
      </TextCell>
    ))}
  </Main>
) : null;
};

如果需要单独提取所有url组成一个一维列表,可使用flatMap直接处理:

// 提取所有url到一个数组
const allUrlList = pressReleases?.flatMap(item => 
  item.content.attachments?.map(attachment => attachment.url)
)?.filter(Boolean) || [];

// 遍历打印所有url
allUrlList.forEach(url => console.log(url))

补充说明:

  • 代码中使用可选链运算符?.可以避免attachments字段不存在时程序抛出异常
  • 遍历数组时需要为每个子元素添加唯一key属性,避免React渲染警告

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:00:00