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

Next.js 13 App目录下Navbar组件如何获取URL的slug参数?

解决Next.js 13 App Router中Navbar获取URL slug的问题

在Next.js 13的/app目录(App Router)中,next/navigation提供的useRouter和Pages Router(Next.js 12及之前)的useRouter完全不同——它没有query属性,这就是你之前的代码无效的核心原因。下面是两种可靠的解决方案:

方案一:通过usePathname拆分路径获取slug

如果你的slug位于URL的一级路径(比如localhost:3000/:slug),可以直接拆分pathname字符串来提取:

// components/Navbar.jsx
import { usePathname } from 'next/navigation';
import { useEffect } from 'react';

export default function Navbar() {
  const pathname = usePathname();
  // 拆分路径:比如pathname为'/my-slug',拆分后得到['', 'my-slug'],取索引1的元素
  const slug = pathname.split('/')[1] || '';

  useEffect(() => {
    console.log('当前slug:', slug);
  }, [pathname]); // 依赖pathname,路由切换时自动触发更新

  return <p>Slug: {slug}</p>;
}

方案二:用正则匹配更复杂的路径结构

如果你的slug位于更深层级(比如localhost:3000/posts/:slug),可以用正则表达式精准匹配:

// components/Navbar.jsx
import { usePathname } from 'next/navigation';
import { useEffect } from 'react';

export default function Navbar() {
  const pathname = usePathname();
  // 正则匹配/posts/后的非斜杠字符(即slug)
  const matchResult = pathname.match(/^\/posts\/([^/]+)$/);
  const slug = matchResult ? matchResult[1] : '';

  useEffect(() => {
    console.log('当前slug:', slug);
  }, [pathname]);

  return <p>Slug: {slug}</p>;
}

关键注意点

  • 必须用usePathname获取当前路径,它会在客户端路由切换时自动更新,解决了window.location.pathname仅刷新才变化的问题。
  • 确保把pathname加入useEffect的依赖数组,这样路由切换时组件会重新计算slug并执行副作用逻辑。

内容的提问来源于stack exchange,提问作者Vivaan Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:15:30