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

Next.js App Router下getStaticProps无返回值问题求助

问题原因与解决方案

核心问题

你用的是Next.js App Router,但代码里用了Pages Router专属的getServerSideProps(包括你提到的getStaticProps)——这俩API在App Router里完全不生效,所以页面组件根本拿不到返回的props,categories自然是undefined。

修复方法

App Router里的页面组件默认是服务器组件,可以直接在组件内部异步获取数据,不需要额外的getStaticProps/getServerSideProps函数。修改你的app/page.js如下:

import Landing from '@/components/Landing'
import Categories from '@/components/Categories'

// App Router页面默认是服务器组件,直接在组件内异步请求数据
export default async function Home() {
  // 发起请求,可根据需求设置缓存策略
  const res = await fetch('https://fakestoreapi.com/products/categories', {
    // 默认是force-cache,对应原getStaticProps的静态生成效果
    // 如果需要每次请求都拉新数据(对应原getServerSideProps),改成cache: 'no-store'
    // 或者用revalidate: 60实现增量静态再生,即每60秒更新一次数据
    cache: 'force-cache'
  });
  const categories = await res.json();

  console.log("cat from home", categories)

  return (
    <div className='home'>
      <Landing />
      <Categories categories={categories} />
    </div>
  )
}

额外说明

  • 你的Categories组件标记了"use client"作为客户端组件,接收父组件传过来的categories props完全没问题,不需要修改。
  • 若要实现原getStaticProps的静态预渲染效果,保持cache: 'force-cache'即可(这是fetch的默认值);若要实现原getServerSideProps的动态渲染效果,设置cache: 'no-store'或者在组件顶部添加export const revalidate = 0;。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 10:01:04