使用应用程序文件夹中的 Next.js 读取 URL 动态参数/slug

Cap*_*i-N 6 javascript reactjs next.js

我在获取动态路由中的参数时遇到问题。我在阅读时不断收到错误:

类型错误:无法解构“router.query”的属性“themenID”,因为它未定义。

另外,我不能使用next/router但必须集成路由器next/navigation。但这个没有查询属性。我使用 Next.js 版本 13

该路径的名称如下:http://localhost:3000/MainThema/2

应用程序/MainThema/[themenID]/page.js:

"use client";
import { useRouter } from "next/navigation";
import React from "react";

export default function MainThema() {
  const router = useRouter();
  console.log(router);

  const { themenID } = router.query;

  return <div>MainThema </div>;
}
Run Code Online (Sandbox Code Playgroud)

You*_*mar 14

正如您在文档中所读到的那样,当您的组件位于动态段中时,它page.js会传递一个对象。paramsparams将包含您的动态路线 ID,如下所示:

// app/MainThema/[themenID]/page.js

export default function MainThema({ params }) {
  const { themenID } = params;

  return <div>{themenID}</div>;
}
Run Code Online (Sandbox Code Playgroud)

如果您需要在某些嵌套的客户端组件中获取它,您应该使用钩子useParams

// app/MainThema/[themenID]/page.js

export default function MainThema({ params }) {
  const { themenID } = params;

  return <div>{themenID}</div>;
}
Run Code Online (Sandbox Code Playgroud)