英文:
how to query items from useRouter() hock in case i'm using nextjs with App Router approach
问题
以下是您要翻译的内容:
这是使用 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>这是第 {listingId} 项</div>;
}
export default ShowroomListings;
现在我从 "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>这是第 {listingId} 项</div>;
}
export default ShowroomListings;
英文:
This was the way to do it using 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;
Now I imported useRouter from "next/navigation" this time, but '.query' will not work anymore
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;
答案1
得分: 1
useRouter
只在客户端组件上起作用(而您的组件是服务器端组件)。您可以在文件的顶部添加 'use client'
指令以使用 useRouter
。
更新:
query
对象已被移除,替代方案是使用useSearchParams
参考:
英文:
useRouter
only works on client-component (while your component is a server-component). You can add 'use client'
directive to top of the file to use useRouter
.
Update:
- The
query
object has been removed and is replaced byuseSearchParams
Reference:
答案2
得分: 0
以下是已翻译的部分:
"it worked for me"
"只是传递正确的动态路由值"
英文:
it worked for me
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
import React from "react";
type ShowroomProps = {
params: {
listingId: string;
};
};
export default function ShowroomListings({
params: { listingId },
}: ShowroomProps) {
return <div>This is item No. {listingId}</div>;
}
<!-- end snippet -->
just passing the right dynamic route value
答案3
得分: 0
不能在服务器组件中使用useRouter钩子,因为它是一个客户端钩子。您需要将您的组件设置为客户端以获取查询参数。
'使用客户端'
此外,Next.js引入了用于查询参数的新钩子useSearchParams,您可以轻松地获取查询参数。
const params = useSearchParams()
params.get("query-parameter-name")
英文:
You cannot use useRouter hook in server component, because it is a client side hook. You need to make you component client inorder to get query parameters.
'use client'
also nextjs introduce new hook for query parameters which is useSearchParams, you can easily get query param with.
const params = useSearchParms()
params.get("query-parameter-name")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论