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

从Jekyll迁移到Next.js:如何生成完整博客分页静态页面?

解决Next.js静态导出分页页面不全的问题

你的核心问题是**getStaticPaths只手动指定了page2的路径**,导致静态构建时仅生成这一个分页页面。下面是具体的修复方案:

1. 动态生成所有分页路径

修改getStaticPaths函数,先获取所有文章计算总页数,再自动生成所有分页的路径:

export async function getStaticPaths() {
  const allPosts = getAllPosts();
  const postsPerPage = 10;
  // 计算总页数
  const totalPages = Math.ceil(allPosts.length / postsPerPage);
  
  // 生成从第2页到最后一页的路径(第1页对应index.js)
  const paths = Array.from({ length: totalPages - 1 }, (_, index) => ({
    params: { id: String(index + 2) }
  }));

  return {
    paths,
    fallback: false // 所有分页都预先生成,无需 fallback
  };
}

2. 在getStaticProps中预处理分页数据

把分页数据的计算逻辑移到getStaticProps中,避免在组件中依赖路由查询参数,同时确保每个静态页面都拿到对应的数据:

export async function getStaticProps({ params }) {
  const allPosts = getAllPosts();
  const postsPerPage = 10;
  // 解析当前页码
  const currentPage = parseInt(params.id, 10);
  // 计算当前页文章的起始/结束索引
  const postStart = (currentPage - 1) * postsPerPage;
  const postEnd = postStart + postsPerPage;
  // 获取当前页的文章列表
  const currentPosts = allPosts.slice(postStart, postEnd);

  return {
    props: { 
      currentPosts,
      allPosts,
      currentPage
    },
  };
}

3. 简化组件逻辑

组件直接使用getStaticProps传递的props,无需再处理路由和数据切片:

import Navbar from '../components/Navbar';
import PostListing from '../components/PostListing';
import PostPagination from '../components/PostPagination';
import RightSideBar from '../components/RightSideBar';

export default function Page({ currentPosts, allPosts, currentPage }) {
  return (
    <>
      <Navbar />
      <div className="container">
        <main>
          <div className="row ">
            <div className="col-sm-8 p-5">
              <PostListing posts={currentPosts} />
              <PostPagination posts={allPosts} currentPage={currentPage - 1} />
            </div>
            <div className="col-sm-4 p-5 no_toc_section ">
              <RightSideBar />
            </div>
          </div> 
        </main>
      </div>
    </>
  );
}

关键说明

  • 原来的postEnd计算有误:(currentPageNumber * 10 + 9) - 10会导致每页仅展示9篇文章,改为postStart + 10符合slice左闭右开的特性,确保每页展示10篇。
  • 设置fallback: false后,所有分页路径都会在静态导出时预先生成,访问时直接返回静态HTML,无需动态生成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:51:32