如何在getStaticProps中无需React Hook获取多级Slug查询Prisma
页面构建前通过getStaticProps()从Prisma按ID(Slug)获取文章
问题核心
你遇到的关键问题是:getStaticProps是构建时/服务端运行的函数,无法使用React Hook(比如useRouter),但多级Slug可以直接从getStaticProps的上下文参数中获取,无需依赖客户端路由。
解决方案
1. 从getStaticProps的context中提取多级Slug
你的路由是/post/[...slugs].tsx(动态捕获所有后续路径段),在getStaticProps里,context.params.slugs会是一个数组,对应URL中/post/后的所有路径部分。比如localhost:3000/post/b513-ad29e3cc67d9/Post%20Title对应的slugs数组就是['b513-ad29e3cc67d9', 'Post Title'],取第一个元素就是你需要的postID。
2. 修正后的完整代码
import { Post, PrismaClient } from '@prisma/client'; import { GetStaticPaths, GetStaticProps } from 'next'; type PostByIdProps = { postById: Post; }; export default function PostDetail({ postById }: PostByIdProps) { return ( <> <div>{postById.title}</div> </> ); } export const getStaticProps: GetStaticProps<PostByIdProps> = async (context) => { // 从context参数中获取多级slug数组 const slugs = context.params?.slugs as string[]; // 处理无效路径 if (!slugs || slugs.length === 0) { return { notFound: true }; } const postId = slugs[0]; // 取第一个元素作为查询用的postID // 初始化Prisma并执行查询 const prisma = new PrismaClient(); const postById = await prisma.post.findUnique({ where: { postId: postId, }, }); // 文章不存在时返回404 if (!postById) { return { notFound: true }; } // 必须返回包含props的对象,这是getStaticProps的要求 return { props: { postById }, revalidate: 60, // 可选:设置增量静态重新生成的缓存有效期(秒) }; }; export const getStaticPaths: GetStaticPaths<{ slugs: string[] }> = async () => { return { paths: [], // 构建阶段不预生成任何页面 fallback: 'blocking', // 访问未预生成的路径时,先服务端渲染再缓存结果 }; };
关键修正点
- 移除了
useRouter的导入和使用,改用context.params.slugs获取路径参数 - 给
getStaticProps和getStaticPaths指定了正确的泛型类型,保证类型安全 - 增加了异常处理:无效路径或文章不存在时返回
notFound: true,避免页面报错 - 给
prisma.post.findUnique添加了await,确保异步查询完成后再返回数据 - 修正了
getStaticProps的返回格式:必须返回包含props的对象,之前直接返回postById不符合Next.js的要求
内容的提问来源于stack exchange,提问作者kawa
相关产品推荐
相关产品推荐

