Next.js 中实现上一篇文章和下一篇文章
假设你的文章数据存储在一个数组中,每篇文章都有一个唯一的 slug 标识符和一个 num 属性表示在数组中的位置。以下是一个示例实现:
import { GetStaticProps } from 'next';
import { getSortedPosts, getPostData, total } from '../lib/posts';
interface Props {
ma: any;
chat: any;
totalPosts: number;
totalWordCount: number;
currentIndex: number;
prev: any;
next: any;
}
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; // 如果找不到对应文章,则返回 0
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();
const prevPost = prevPostIndex >= 0 ? posts[prevPostIndex] : null;
const nextPost = nextPostIndex < posts.length ? posts[nextPostIndex] : null;
return {
props: {
ma,
chat,
totalPosts,
totalWordCount,
currentIndex,
prev: prevPost,
next: nextPost,
}
}
}
在这里,我们首先获取所有文章,并找到当前文章的位置。然后,我们计算出上一篇文章和下一篇文章的位置,并在返回的 props 中包含它们的数据。如果当前文章是第一篇文章,则 prev 为 null;如果当前文章是最后一篇文章,则 next 为 null。在模板中,您可以使用这些数据来创建上一页和下一页的链接。
原文地址: https://www.cveoy.top/t/topic/mATV 著作权归作者所有。请勿转载和采集!