You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 11:50:04