如何在 Next.js 博客文章中实现 '上一篇文章' 和 '下一篇文章' 链接?

为了实现 '上一篇文章' 和 '下一篇文章' 的链接功能,需要在 getStaticProps 函数中获取所有文章列表,并根据当前文章的位置确定前一篇和后一篇文章的链接。具体步骤如下:

  1. 获取所有文章列表:可以使用 getSortedPosts 函数等方法获取所有文章数据。

  2. 查找当前文章位置:根据 params 中的 slug 获取当前文章的位置,可以使用 Arrayfind 方法查找。

  3. 计算前一篇和后一篇文章的位置:根据当前文章的位置,可以直接计算或使用 currentIndex - 1currentIndex + 1 计算前一篇和后一篇文章的位置。

  4. 生成链接:根据前一篇和后一篇文章的位置确定链接,可以使用 Link 组件等方法实现。

最后,将获取到的前一篇和后一篇文章的链接传递给组件即可。

以下代码片段展示了如何在 getStaticProps 函数中实现 '上一篇文章' 和 '下一篇文章' 链接的示例:

export const getStaticProps: GetStaticProps = async ({ params }) => {
  if (!params || !params.slug) {
    return { notFound: true };
  }
  const originalSlug = params?.slug?.toString().split(',').join('/')
  const slug = originalSlug.replace(/\.html$/, '')

  const posts = await getSortedPosts();
  const currentPost = posts.find(post => post.slug.toString().split(',').join('/').replace(/\.html$/, '') === slug);
  const currentIndex = currentPost?.num ?? 0; // 如果找不到对应文章,则返回 -1

  const prevPostIndex = currentIndex - 1;
  const nextPostIndex = currentIndex + 1;
  
  const ma = await getPostData(slug as string);
  const chat = await chatGPTData(slug as string);

  const { totalPosts, totalWordCount } = await total();
  return {
    props: {
      ma,
      chat,
      totalPosts,
      totalWordCount,
      currentIndex,
      prev,
      next,
    }
  }
}

注意:

  • prevnext 是需要在组件中定义的变量,用于存储前一篇和后一篇文章的链接。
  • Link 组件需要根据实际情况进行修改,例如使用 Next.js 的 Link 组件或其他路由组件。

通过以上步骤,就可以在 Next.js 博客文章中实现 '上一篇文章' 和 '下一篇文章' 的链接功能了。

Next.js 博客文章:实现上一篇文章和下一篇文章的链接

原文地址: https://www.cveoy.top/t/topic/mAR9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录