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

Next.js用getStaticProps获取API数据报错Cannot read properties of undefined (reading 'map')

问题根因

1. getStaticProps 生效范围错误

Next.js 中 getStaticProps 仅支持在pages 目录下的路由页面组件中使用,如果你当前的 Images 组件是存放在 components 目录下的普通业务组件,getStaticProps 不会被框架执行,传入组件的 hotelPics 自然为 undefined。添加可选链操作符只会避免调用 map 时报错,不会修复参数不存在的问题,因此控制台会打印 undefined。

2. API 返回结构不匹配

你请求的接口返回值顶层是酒店对象数组,而非直接的图片数组。每个酒店对象下的 images 字段才是你需要的图片列表,直接将接口返回值赋值给 hotelPics 会导致数据结构和预期不符,无法正确遍历拿到图片 URL。

3. Next.js Image 组件配置缺失(后续渲染报错的潜在原因)

原生 next/image 组件要求必填 width、height 参数,或指定 layout 属性,同时需要将图片资源的域名添加到项目配置的白名单中,否则即使拿到正确的图片 URL 也无法正常渲染。

解决方案
  • 调整 getStaticProps 位置:如果 Images 是普通组件,将 getStaticProps 逻辑迁移到它所属的 pages 路由页面中,在页面层获取数据后通过 props 传递给 Images 组件。
  • 校正数据取值层级:在 getStaticProps 中处理接口返回值,提取你需要的图片列表,示例代码如下:
export async function getStaticProps() {
  const res= await fetch ('https://obmng.dbm.guestline.net/api/hotels?collection-id=OBMNG')
  const hotels = await res.json()
  // 提取所有酒店的图片数组,扁平化处理为一维数组
  const hotelPics = hotels.flatMap(hotel => hotel.images || [])
  return {
    props: {
      hotelPics,
    },
  }
}
  • 补充 Image 组件和项目配置:
  1. 在项目根目录的 next.config.js 中添加图片域名白名单:
module.exports = {
  images: {
    domains: ['obmng.dbm.guestline.net'],
  },
}
  1. 完善 Image 组件参数,添加兜底渲染逻辑避免报错:
import Image from 'next/image';
import React from 'react'

// 给hotelPics设置默认空数组兜底
function Images({hotelPics = []}) {
  console.log(hotelPics);
  return (
    <div>
      {hotelPics.map((hotelpic, index)=> (
        <Image 
          key={index}
          src={hotelpic.url}
          width={300}
          height={200}
          alt="酒店图片"
        />
      ))}    
    </div>
  )
}

export default Images

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:54:01