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

React中嵌套map无法访问API数据,报Cannot read properties of undefined错误

问题

在React项目中使用嵌套map遍历数据时,无法正确访问第二组数据。每个对象可包含多个spaces,但遍历spaces时出现错误:Cannot read properties of undefined (reading 'map')。可自行修改接口数据结构。

接口返回数据示例:

{
 "title": "Libreria",
 "id": 23822,
 "link": "https://second-home.local/location/libreria/",
 "spaces": [
  {
   "title": "The Bookshop",
   "id": 475,
   "description": "A little labyrinth of literature.",
   "recommended": "Great for talks and launches",
   "capacity": "Up to 70 standing"
  }
 ]
}

React代码片段:

{locations.length > 0 ? (
    <div className="locations-listing__grid">
        {locations.map((location) => (
            <React.Fragment>
                <div className="locations-listing__header">
                    <h2 className="locations-listing__title">{location.title}</h2>
                </div>
                {location.spaces.map((space, key) => (
                    <LocationCard
                        key={key}
                        location={location}
                        space={space}
                        title={space.title}
                        id={space.id}
                        link={space.link}
                        image-url={space.image.url}
                        description={space.description}
                        recommended={space.recommended}
                        capacity={space.capacity}
                    />
                ))}
            </React.Fragment>
        ))}
    </div>
) : (
    <div className="locations-listing__no-results">
        <h3>No locations found</h3>
    </div>
)}
解决方案
  • 添加空值校验:在调用map前先确保location.spaces存在,用可选链操作符或空值兜底:

    // 方式1:空值合并运算符兜底为空数组
    {(location.spaces || []).map((space, key) => (...))}
    // 方式2:可选链操作符,不存在时直接不执行map
    {location.spaces?.map((space, key) => (...))}
    

    这样即使某个location没有spaces字段,也不会触发报错。

  • 统一数据结构:在处理接口返回数据时,提前给每个location补充spaces默认值,避免出现undefined:

    const processedLocations = locations.map(location => ({
      ...location,
      spaces: location.spaces ?? []
    }));
    

    之后用processedLocations来遍历渲染。

  • 调整接口规范:修改接口,保证所有location对象的spaces字段始终是数组类型——哪怕是空数组,彻底从源头避免字段缺失问题。

  • 修正组件传参:注意代码里LocationCard用到的space.link和space.image.url,在接口示例的space对象里没有这两个字段,会导致新的报错,需要同步接口数据或者调整传参逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 09:01:09