Next.js App Router中如何用useRouter钩子获取查询参数?
Next.js App Router 中获取路由查询参数的方法
在App Router模式下,从next/navigation导入的useRouter不再提供query属性,需要通过以下两种方式获取路由查询参数:
1. 客户端组件中使用 useSearchParams 钩子
如果你的组件是客户端组件(需要交互或使用hooks),使用useSearchParams来获取查询参数,注意必须添加'use client'指令:
'use client'; import { useSearchParams } from 'next/navigation'; import React from 'react'; export default function ShowroomListings() { const searchParams = useSearchParams(); // 获取单个查询参数,返回值可能为null,可根据需要做类型断言 const listingId = searchParams.get('listingId') as string; // 若要获取所有查询参数并转为对象 const allParams = Object.fromEntries(searchParams.entries()); return <div>This is item No. {listingId}</div>; }
2. 服务器组件中直接通过 searchParams props 获取
服务器组件无需使用hooks,页面组件或布局组件可以直接接收searchParams参数:
// app/showroom-listings/page.tsx export default function ShowroomListings({ searchParams, }: { searchParams: { [key: string]: string | string[] | undefined }; }) { // 获取单个参数,根据实际情况处理类型 const listingId = searchParams.listingId as string; return <div>This is item No. {listingId}</div>; }
注意事项
useSearchParams仅能在客户端组件中使用,必须添加'use client'指令,否则会触发编译错误。searchParams.get()返回的是字符串或null,如果确定参数一定存在,可以用类型断言处理。- 若查询参数有多个值(如
?tag=foo&tag=bar),可以使用searchParams.getAll('tag')获取数组。
内容的提问来源于stack exchange,提问作者Anas Ghareib
相关产品推荐
相关产品推荐

