此问题已在此处有答案:
Read URL dynamic parameter/slug with Next.js in the app folder(1个答案)
How to get the current pathname in the app directory of Next.js 13?(1个答案)
9天前关闭
这是使用Pages Router的方法
import { useRouter } from "next/router";
import React from "react";
function ShowroomListings({}) {
const router = useRouter();
const { listingId } = router.query as { listingId: string };
return <div>This is item No. {listingId}</div>;
}
export default ShowroomListings;
Failed to compile message
现在我这次从“next/navigation”导入useRouter,但是'.query'将不再工作
import { useRouter } from "next/navigation";
import React from "react";
function ShowroomListings({}) {
const router = useRouter();
const { listingId } = router.query as { listingId: string };
return <div>This is item No. {listingId}</div>;
}
export default ShowroomListings;
3条答案
按热度按时间fdx2calv1#
useRouter
只适用于客户端组件(而您的组件是服务器组件)。您可以将'use client'
指令添加到文件的顶部以使用useRouter
。更新:
query
对象已被删除,替换为useSearchParams
参考文献:
qojgxg4l2#
对我很有效
传递正确的动态路由值
polkgigr3#
不能在服务器组件中使用useRouter钩子,因为它是客户端钩子。您需要使您的组件客户端,以便获得查询参数。
nextjs还为查询参数引入了新的钩子,即useSearchParams,你可以很容易地获得查询参数。