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

NextJS App Router中getServerSideProps不支持的报错解决及替代方案

问题解决:App Router中无法使用getServerSideProps的处理方案

报错原因

getServerSideProps是Next.js Pages Router(pages目录) 专属的服务端数据获取API,而你当前使用的是App Router(app目录),两者架构与数据获取逻辑完全不同,直接套用会触发报错。

解决方案:App Router中实现等效的服务端数据获取

在App Router中,页面组件默认是服务器组件,可直接在组件内部编写异步代码获取数据,效果和getServerSideProps完全一致(每次请求都会在服务器端执行数据获取,返回渲染后的页面)。

修改后的代码示例:

// app/page.tsx
type Repo = {
  name: string
  stargazers_count: number
}

// 直接在页面组件中编写异步数据获取逻辑
export default async function Page() {
  const res = await fetch('https://api.github.com/repos/vercel/next.js', {
    // 可选:配置强制实时获取,完全匹配getServerSideProps的行为
    // next: { revalidate: 0 }
  })
  const repo: Repo = await res.json()
  
  return <div>{repo.stargazers_count}</div>
}

进阶:获取请求参数(路由/查询参数)

如果需要像getServerSideProps那样访问路由参数、查询参数,可直接在页面组件的参数中解构:

export default async function Page({ params, searchParams }: {
  params: { id: string }
  searchParams: { [key: string]: string | string[] | undefined }
}) {
  // 使用参数请求对应数据
  const res = await fetch(`https://api.github.com/repos/${params.id}`)
  const repo = await res.json()
  
  return <div>{repo.name}</div>
}

注意事项

  • 服务器组件中不能使用React Hooks(如useState、useEffect),若需要客户端交互功能,需将交互部分抽离为客户端组件(添加'use client'指令)。
  • 可通过fetch的next配置项灵活控制缓存策略,比如revalidate: 60表示每60秒重新获取一次数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:13:27