Menu

usePathname

usePathname 是一个 客户端组件 hook,允许你读取当前 URL 的 路径名

app/example-client-component.tsx
"use client";
 
import { usePathname } from "next/navigation";
 
export default function ExampleClientComponent() {
  const pathname = usePathname();
  return <p>当前路径名: {pathname}</p>;
}
app/example-client-component.js
"use client";
 
import { usePathname } from "next/navigation";
 
export default function ExampleClientComponent() {
  const pathname = usePathname();
  return <p>当前路径名: {pathname}</p>;
}

usePathname 有意要求使用 客户端组件。需要注意的是,客户端组件并不是一种优化上的缺陷。它们是 服务端组件 架构的重要组成部分。

例如,带有 usePathname 的客户端组件在初始页面加载时会被渲染成 HTML。当导航到新路由时,这个组件不需要重新获取。相反,该组件在客户端 JavaScript 包中下载一次,并根据当前状态重新渲染。

值得注意的是:

  • 服务端组件 中读取当前 URL 是不支持的。这一设计是有意为之,以支持布局状态在页面导航之间保持不变。
  • 兼容模式:
    • usePathname 在渲染 回退路由 或当 pages 目录页面被 Next.js 自动静态优化 并且路由器未就绪时,可能返回 null
    • Next.js 会自动更新你的类型,如果它检测到你的项目中同时存在 apppages 目录。

参数

const pathname = usePathname();

usePathname 不接受任何参数。

返回值

usePathname 返回当前 URL 路径名的字符串。例如:

URL返回值
/'/'
/dashboard'/dashboard'
/dashboard?v=2'/dashboard'
/blog/hello-world'/blog/hello-world'

示例

响应路由变化执行某些操作

app/example-client-component.tsx
"use client";
 
import { usePathname, useSearchParams } from "next/navigation";
 
function ExampleClientComponent() {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  useEffect(() => {
    // 在这里执行某些操作...
  }, [pathname, searchParams]);
}
app/example-client-component.js
"use client";
 
import { usePathname, useSearchParams } from "next/navigation";
 
function ExampleClientComponent() {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  useEffect(() => {
    // 在这里执行某些操作...
  }, [pathname, searchParams]);
}
版本变更
v13.0.0usePathname 引入。