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

Next.js(React+TypeScript)中getStaticProps请求API数据失败怎么办

问题修复方案

你的代码无法正常拿到数据,核心是3个可直接复现的问题,对应修改即可:

  • 类型定义和接口返回不匹配:接口返回的price字段是数值类型,你定义成了string,TypeScript校验失败时会直接阻断Next.js的渲染流程。
  • 缺少请求错误处理:原生fetch仅在网络完全不通时抛出异常,接口返回4xx/5xx状态码时不会主动报错,未做状态校验会导致拿到异常响应时直接渲染崩溃。
  • 路由模式不匹配:getStaticProps仅在Next.js的Pages Router下生效,如果你用的是Next.js 13+默认的App Router,这个方法不会被框架执行,自然无法向组件传递props。

Pages Router 对应修正代码

如果你使用Pages Router(页面文件写在pages目录下),直接替换为以下代码即可:

import React from 'react'

interface Product {
  id: number
  title: string
  price: number
  category: string
  description: string
  image: string
}

interface Props {
  products: Product[]
}

export const getStaticProps = async () => {
  try {
    const response = await fetch("https://fakestoreapi.com/products")
    if (!response.ok) {
      throw new Error(`请求异常,状态码:${response.status}`)
    }
    const products = await response.json()

    return {
      props: { products },
      revalidate: 60
    }
  } catch (err) {
    console.error('商品数据获取失败:', err)
    return {
      props: { products: [] }
    }
  }
}

const FetchProducts = ({ products }: Props) => {
  return (
    <div>
      <h1>商品列表</h1>
      {products.length === 0 ? (
        <p>暂无商品数据</p>
      ) : (
        products.map(product => (
          <div key={product.id}>
            {product.title}
          </div>
        ))
      )}
    </div>
  )
}

export default FetchProducts

App Router 对应修正代码

如果你使用Next.js 13+的App Router(页面文件写在app目录下),getStaticProps已经不适用,直接在服务端组件内请求数据即可:

// app/fetch-products/page.tsx
async function fetchProducts() {
  const res = await fetch("https://fakestoreapi.com/products", {
    next: { revalidate: 60 }
  })
  if (!res.ok) return []
  return res.json()
}

export default async function FetchProductsPage() {
  const products = await fetchProducts()

  return (
    <div>
      <h1>商品列表</h1>
      {products.length === 0 ? (
        <p>暂无商品数据</p>
      ) : (
        products.map((product: {id: number, title: string}) => (
          <div key={product.id}>{product.title}</div>
        ))
      )}
    </div>
  )
}

调试提示:getStaticProps的执行环境是Node服务端,你写的console.log不会输出在浏览器控制台,只会打印在运行npm run dev/npm run build的终端窗口里。

内容的提问来源于stack exchange,提问作者Nicholas Darko Brown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 14:40:00