跳到主要內容
API 參考函式usePathname

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>Current pathname: {pathname}</p>
}

usePathname 有意要求使用客戶端元件。務必注意,客戶端元件並非反最佳化。它們是 伺服器元件 架構不可或缺的一部分。

例如,具有 usePathname 的客戶端元件將在初始頁面載入時渲染成 HTML。當導航到新路由時,此元件不需要重新抓取。相反地,元件會下載一次(在客戶端 JavaScript 捆綁包中),並根據目前狀態重新渲染。

要知道:

  • 不支援從伺服器元件讀取目前 URL。此設計是有意為之,旨在支援跨頁面導航保留版面配置狀態。
  • 相容性模式
    • 後備路由正在渲染,或者當 pages 目錄頁面已被 Next.js 自動靜態最佳化,且路由器尚未就緒時,usePathname 可能會回傳 null
    • next.configMiddleware 中使用 usePathname 進行 rewrites 時,也必須使用 useStateuseEffect,以避免 hydration 不符錯誤。請參閱 rewrites 範例 以取得更多資訊。
    • 如果 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(() => {
    // Do something here...
  }, [pathname, searchParams])
}
版本變更
v13.0.0引入 usePathname