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

Next.js14 SSG预渲染页面构建后仍有5秒延迟问题求助

问题原因分析

你的动态路由页面src/app/posts/[slug].tsx在build后仍存在5秒延迟,核心原因是getArticles函数中的fetch配置了cache: 'no-store'——这个参数会强制禁用Next.js的缓存机制,导致每次用户访问页面时,都会重新发起API请求,而不是使用build阶段预渲染好的静态数据。

另一个标记为「Static」的页面没有这个问题,是因为它的API调用没有禁用缓存,build时就把数据预渲染到静态HTML中,访问时直接加载,无需再调用API。

修复方案

方案一:移除缓存禁用配置

直接去掉fetch的cache: 'no-store'参数,让Next.js默认缓存API响应(默认行为等价于cache: 'force-cache'):

async function getArticles() {
  // 移除cache: 'no-store',允许Next.js缓存请求结果
  const res = await fetch('http://localhost:5001/posts');
  return res.json();
}

修改后重新执行npm run build,Next.js会在build阶段预渲染所有动态路由页面的静态HTML,启动npm run start后访问页面时,会直接加载预渲染好的内容,不再发起API请求,5秒延迟消失。

方案二:预传递文章数据到组件

如果需要保留特定缓存策略,也可以在generateStaticParams中预获取所有文章数据,直接传递给组件,避免组件重复调用API:

import Link from 'next/link';

type Article = {
  title: string;
  summary: string;
};

type ArticlePageProps = {
  params: { 
    slug: string;
    article: Article;
  };
};

async function getArticles() {
  const res = await fetch('http://localhost:5001/posts', { cache: 'no-store' });
  return res.json();
}

// 修改generateStaticParams,返回包含文章数据的参数
export async function generateStaticParams() {
  const articles = await getArticles();
  return articles.posts.map((article: Article) => ({
    slug: encodeURIComponent(article.title),
    article: article,
  }));
}

// 组件直接使用params中的文章数据,无需再调用API
const ArticlePage = ({ params: { article }}: ArticlePageProps) => {
  if (!article) {
    return <div>Article not found</div>;
  }

  return (
    <div className="max-w-4xl mx-auto py-8">
      <h1 className="text-3xl font-bold mb-6 text-center">Article Details</h1>
      <h2 className="text-xl text-center">{article.title}</h2>
      <p className="font-light text-amber-200 text-center mt-4">{article.summary}</p>
      <div className="mt-8 text-center">
        <Link href="/posts" className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">
          Back to Posts
        </Link>
      </div>
    </div>
  );
};

export default ArticlePage;

这种方式下,build阶段会将每篇文章的数据直接嵌入到对应静态页面中,访问时无需再发起API请求,彻底消除延迟。

可选:增量静态再生(ISR)

如果需要定期更新页面数据,同时避免每次访问都重新请求API,可以将cache: 'no-store'替换为next: { revalidate: 60 }(示例为60秒重新验证一次数据):

async function getArticles() {
  const res = await fetch('http://localhost:5001/posts', { 
    next: { revalidate: 60 } // 每60秒重新获取一次数据
  });
  return res.json();
}

这样页面会在build时预渲染,之后每60秒自动重新生成静态页面,兼顾静态页面的加载速度和数据新鲜度。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 01:16:05