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

Next.js调用API请求时报错"banner.map is not a function"如何解决

问题根因

你调用的https://fortnite-api.com/v1/banners接口返回的不是直接的横幅对象数组,接口响应是外层包裹了标准响应结构的对象:

{
  "status": 200,
  "data": [/* 这里才是你需要的横幅数组 */]
}

你当前把整个响应对象赋值给了banners变量,对象类型没有map方法,所以会抛出对应报错。

修复方案

  1. 修改getStaticProps中的取值逻辑,取响应体的data字段作为banners的值,同时添加请求错误处理
  2. 组件中调用map前添加非空校验,避免边界场景报错

修复后完整代码

export const getStaticProps = async () => {
  try {
    const res = await fetch('https://fortnite-api.com/v1/banners');
    const result = await res.json();
    // 取响应里的data字段才是目标数组
    return {
      props: { banners: result.data || [] }
    }
  } catch (e) {
    // 请求异常时返回空数组兜底
    return {
      props: { banners: [] }
    }
  }
}

const FortniteApi = ({ banners }) => {
  return (
    <div>
      <h1>Fortnite Api</h1>
      {/* 可选链调用,避免banners为非数组时报错 */}
      {banners?.map(banner => (
        <div key={banner.id}>
          <a>
            <h3>{banner.name}</h3>
          </a>
        </div>
      )) || <div>暂无横幅数据</div>}
    </div>
  )
}

export default FortniteApi

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:27:01