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

如何在Next.js服务端组件中获取URL的params id参数?

服务端组件获取URL参数的方法

Next.js App Router(React Server Components)场景

服务端组件无需客户端钩子,直接通过组件 props 就能获取路由参数:

1. 动态路由参数(如/ferramenta/[id]路径)

如果你的组件对应动态路由文件(比如app/ferramenta/[id]/page.js),直接从params props 中提取id:

import FerramentaCard from '@/components/ferramentas/ferramenta';

export default async function Ferramenta({ params }) {
  // params.id 就是URL里的动态参数
  const response = await fetch(`https://gameinfo.albiononline.com/api/gameinfo/items/${params.id}/data`);
  // 注意:mode: 'no-cors'会导致无法读取响应内容,建议移除该配置
  const ferramentaInfo = await response.json();

  return <FerramentaCard ferramentaInfo={ferramentaInfo} />;
}

2. 查询参数(如/ferramenta?id=xxx路径)

如果是URL中的查询参数,通过searchParams props 获取:

import FerramentaCard from '@/components/ferramentas/ferramenta';

export default async function Ferramenta({ searchParams }) {
  const itemId = searchParams.id;
  const response = await fetch(`https://gameinfo.albiononline.com/api/gameinfo/items/${itemId}/data`);
  const ferramentaInfo = await response.json();

  return <FerramentaCard ferramentaInfo={ferramentaInfo} />;
}

Next.js Pages Router(SSR页面)场景

用getServerSideProps获取参数后传递给组件:

import FerramentaCard from '@/components/ferramentas/ferramenta';

export default function Ferramenta({ ferramentaInfo }) {
  return <FerramentaCard ferramentaInfo={ferramentaInfo} />;
}

export async function getServerSideProps(context) {
  // 动态路由参数取context.params.id,查询参数取context.query.id
  const itemId = context.params.id;
  const response = await fetch(`https://gameinfo.albiononline.com/api/gameinfo/items/${itemId}/data`);
  const ferramentaInfo = await response.json();

  return {
    props: { ferramentaInfo }
  };
}

关键注意事项

  • 务必移除mode: 'no-cors':该配置会让浏览器禁止读取响应内容,即使请求发送成功,response.json()也会报错。
  • 服务端组件不支持客户端钩子(useSearchParams/useRouter),只能通过props获取路由参数。

内容的提问来源于stack exchange,提问作者Dayvson Spacca

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:42:40