How can I pass parameters to a component using the Link component? The following doesn't work. I always get undefined in SinglePost.
如何使用Link组件将参数传递给组件?以下方法不起作用。我在SinglePost上总是不确定。
<Link
key={2}
href={{
pathname: "/singlePost",
query: 2,
}}
id={2}
>
<Post></Post>
</Link>
SinglePost
SinglePost
export default function SinglePost() {
const router = useRouter();
const data = router.query;
//always undefined
console.log(data);
...
}
更多回答
优秀答案推荐
If you are using Next.js 13 app router, then you can achieve this by the following approach
如果您使用的是Next.js 13应用程序路由器,则可以通过以下方法来实现
<Link
key={2}
href={{
pathname: "/singlePost",
query: {id: 2},
}}
id={2}
>
<Post></Post>
</Link>
SinglePost
SinglePost
'use client';
import { useSearchParams } from 'next/navigation';
// ...rest of your imports
export default function SinglePost() {
const id = useSearchParams().get('id');
console.log(id);
...
}
更多回答
我是一名优秀的程序员,十分优秀!