跳到内容

31

实现 getStaticPaths

首先,让我们设置文件

  • pages/posts 目录下创建一个名为 [id].js 的文件。
  • 同时,删除 pages/posts 目录下的 first-post.js —— 我们将不再使用它。

然后,在您的编辑器中打开 pages/posts/[id].js 并粘贴以下代码。稍后我们将填写 ...

import Layout from '../../components/layout';
 
export default function Post() {
  return <Layout>...</Layout>;
}

然后,打开 lib/posts.js 并在底部添加以下 getAllPostIds 函数。它将返回 posts 目录中文件名(不包括 .md)的列表

export function getAllPostIds() {
  const fileNames = fs.readdirSync(postsDirectory);
 
  // Returns an array that looks like this:
  // [
  //   {
  //     params: {
  //       id: 'ssg-ssr'
  //     }
  //   },
  //   {
  //     params: {
  //       id: 'pre-rendering'
  //     }
  //   }
  // ]
  return fileNames.map((fileName) => {
    return {
      params: {
        id: fileName.replace(/\.md$/, ''),
      },
    };
  });
}

重要提示:返回的列表仅仅是字符串数组 —— 它必须是对象数组,看起来像上面的注释。每个对象都必须具有 params 键,并包含一个带有 id 键的对象(因为我们在文件名中使用了 [id])。否则,getStaticPaths 将会失败。

最后,我们将导入 getAllPostIds 函数并在 getStaticPaths 中使用它。打开 pages/posts/[id].js 并在导出的 Post 组件上方复制以下代码

import { getAllPostIds } from '../../lib/posts';
 
export async function getStaticPaths() {
  const paths = getAllPostIds();
  return {
    paths,
    fallback: false,
  };
}
  • paths 包含 getAllPostIds() 返回的已知路径数组,其中包括 pages/posts/[id].js 定义的参数。在 paths 键文档 中了解更多信息
  • 暂时忽略 fallback: false —— 我们稍后会解释。

我们快完成了 —— 但我们仍然需要实现 getStaticProps。让我们在下一页上进行操作!

您已完成章节31

下一步

32: 实现 getStaticProps