Next.js v15动态路由参数TypeScript编译错误求助
Next.js 15 App Router动态路由TypeScript编译错误解决方案
错误原因
你的BlogPage组件参数类型定义错误:将params的类型设置为Promise<{ params: { slug: string } }>,但Next.js App Router中,Page组件接收的是同步的Props对象,而非Promise。async组件本身返回Promise,但参数是直接传入的普通对象,这导致TypeScript类型校验失败。
修复步骤
- 将
BlogPage组件的参数类型替换为你已定义的Props类型 - 删除
await params这行代码,直接解构参数对象
修改后的完整代码
import MaxWidthWrapper from '@/components/MaxWidthWrapper'; import React from 'react'; import { unified } from "unified"; import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; import rehypeSlug from 'rehype-slug'; import rehypeStringify from "rehype-stringify"; import matter from "gray-matter"; import fs from "fs"; import rehypeAutolinkHeadings from 'rehype-autolink-headings'; import { rehypePrettyCode } from 'rehype-pretty-code'; import { transformerCopyButton } from '@rehype-pretty/transformers'; import { Metadata } from 'next'; type Props = { params: { slug: string }; }; // 修正参数类型为Props,去掉Promise包裹 export default async function BlogPage({ params: { slug } }: Props) { const filePath = `content/${slug}.md`; const fileContent = fs.readFileSync(filePath, "utf-8"); const { data, content } = matter(fileContent); const processor = unified() .use(remarkParse) .use(remarkRehype) .use(rehypeSlug) .use(rehypePrettyCode, { theme: "github-dark", transformers: [ transformerCopyButton({ visibility: 'always', feedbackDuration: 3000, }), ], }) .use(rehypeAutolinkHeadings) .use(rehypeStringify); const htmlContent = (await processor.process(content)).toString(); return ( <MaxWidthWrapper className="prose dark:prose-invert"> <div className="px-16"> <h1>{data.title}</h1> <div dangerouslySetInnerHTML={{ __html: htmlContent }}></div> </div> </MaxWidthWrapper> ); } export async function generateMetadata({ params }: Props): Promise<Metadata> { const filePath = `content/${params.slug}.md`; const fileContent = fs.readFileSync(filePath, "utf-8"); const { data } = matter(fileContent); return { title: data.title, description: data.description, openGraph: { images: [ { url: data.imgUrl, }, ], }, }; }
额外说明
generateMetadata函数的参数类型是正确的,不需要修改- 修正后执行
npm run build即可正常编译,访问/blogpost/my-post路由也能正常渲染
内容的提问来源于stack exchange,提问作者eagleadmiral
相关产品推荐
相关产品推荐

