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

Next.js+TypeScript嵌套页面中GetServerSideProps未触发问题

问题解决:Next.js中GetServerSideProps未触发导致数据获取失败

问题现象

  • 在Next.js+TypeScript项目中创建/article/[id]动态路由页面,计划通过GetServerSideProps根据ID拉取文章数据,但该函数完全未执行(控制台无日志输出)
  • 访问页面时因article未定义,触发TypeError: Cannot read properties of undefined (reading 'title')报错
  • 将页面内容替换为静态文本时可正常显示,修改文件名后问题依旧

核心原因

函数名拼写错误:你定义的是getServersideProps,而Next.js要求的正确驼峰命名是getServerSideProps(注意Server和Props的首字母大写)。Next.js仅会识别正确命名的服务器端数据获取函数,拼写错误会导致函数被框架忽略,无法触发执行。

修正后的完整代码

import { GetServerSideProps, NextPage } from 'next'
import Link from 'next/link'

interface Article {
  userId: number;
  id: number;
  title: string;
  body: string;
}

interface ArticleProps {
  article: Article
}

const ArticleDetail: NextPage<ArticleProps> = ({ article }) => {
  return (
    <div>
      <h1>{article.title}</h1>
      <p>{article.body}</p>
      <br />
      <Link href="/">Go Back</Link>
    </div>
  )
}

export default ArticleDetail

// 修正函数名的拼写
export const getServerSideProps: GetServerSideProps = async (context) => {
  console.log("hello"); // 现在会正常输出日志
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${context.params?.id}`)
  const article = await res.json() as Article
  console.log(article); // 现在会正常输出文章数据

  return {
    props: {
      article
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:45:33