gpt4 book ai didi

Next.js link component send parameter = undefined(Next.js链接组件发送参数=未定义)

翻译 作者:bug小助手 更新时间:2023-10-26 22:32:06 25 4
gpt4 key购买 nike



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);

...

}

更多回答

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com