在Nextjs中未定义params?

62o28rlo  于 2023-08-04  发布在  其他
关注(0)|答案(2)|浏览(124)

我在app/api/hello/[slug]/route.ts中有下面的函数
当我控制台日志我得到undefined。为什么?
app/API/hello/[slug]/route.ts

export async function GET({ params }: any) {
    console.log(params);
}

字符串
计程仪

- wait compiling /api/hello/[slug]/route (client and server)...
- event compiled successfully in 308 ms (65 modules)
undefined


x1c 0d1x的数据

qq24tv8q

qq24tv8q1#

因为第一个参数是Request

export async function GET(request: Request) {}

字符串
params是第二个参数(可选)

export async function GET(request: Request, { params }: any) {}


所以最终代码应该是:

export async function GET(request: Request, { params }: any) {
    console.log(params);


您可以通过指定段塞的类型使其具体化

export async function GET(request: Request, { params }: { params: { slug: string } }) {
  console.log(params);
}

oug3syen

oug3syen2#

因为您正在解构Request对象(它没有 params 键)
parameters对象是第二个参数。

export async function GET(request: Request, { params }: { params: { slug: string } }) {
  console.log(request.url, params);
}

字符串
您可以查看NextJS文档中关于动态路由段的内容:https://nextjs.org/docs/app/building-your-application/routing/router-handlers#dynamic-route-segments

相关问题