Next.js 中实现上一篇文章和下一篇文章的完整代码示例
假设你已经有了一个 getSortedPosts() 函数用于获取排序后的文章列表,以及一个 getPostData(slug) 函数用于获取特定 slug 的文章数据。
你可以在 getStaticProps 中使用这些函数来获取当前文章的上一篇和下一篇文章。以下是一个示例代码:
import { GetStaticProps } from 'next';
import { getSortedPosts, getPostData } from '../lib/posts';
type Props = {
ma: any;
chat: any;
totalPosts: number;
totalWordCount: number;
currentIndex: number;
prev?: {
title: string;
slug: string;
};
next?: {
title: string;
slug: string;
};
};
export const getStaticProps: GetStaticProps<Props> = 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;
const prevPost = posts[currentIndex - 1];
const nextPost = posts[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: prevPost && {
title: prevPost.frontmatter.title,
slug: prevPost.slug.toString().split(',').join('/').replace(/\.html$/, ''),
},
next: nextPost && {
title: nextPost.frontmatter.title,
slug: nextPost.slug.toString().split(',').join('/').replace(/\.html$/, ''),
},
},
};
};
在上面的代码中,我们首先通过 getSortedPosts() 获取了排序后的文章列表,然后在 currentPost 中查找当前文章。之后,我们可以使用 currentIndex 计算出上一篇和下一篇文章的索引,并从 posts 中获取对应的文章数据。
最后,我们将上一篇和下一篇文章的标题和 slug 返回给页面组件使用。注意,如果当前文章是列表中的第一篇或最后一篇,则上一篇或下一篇文章为 undefined。
原文地址: https://www.cveoy.top/t/topic/mASs 著作权归作者所有。请勿转载和采集!