跳到主要内容

useRouter

useRouter 钩子允许你以编程方式更改 客户端组件 内的路由。

¥The useRouter hook allows you to programmatically change routes inside Client Components.

推荐:除非你有使用 useRouter 的特定要求,否则请使用 <Link> 组件 进行导航。

¥Recommendation: Use the <Link> component for navigation unless you have a specific requirement for using useRouter.

'use client'

import { useRouter } from 'next/navigation'

export default function Page() {
const router = useRouter()

return (
<button type="button" onClick={() => router.push('/dashboard')}>
Dashboard
</button>
)
}
'use client'

import { useRouter } from 'next/navigation'

export default function Page() {
const router = useRouter()

return (
<button type="button" onClick={() => router.push('/dashboard')}>
Dashboard
</button>
)
}

useRouter()

  • router.push(href: string, { scroll: boolean }):对所提供的路由执行客户端导航。将新条目添加到 浏览器的历史记录 堆栈中。

    ¥router.push(href: string, { scroll: boolean }): Perform a client-side navigation to the provided route. Adds a new entry into the browser’s history stack.

  • router.replace(href: string, { scroll: boolean }):对所提供的路由执行客户端导航,而无需在 浏览器的历史堆栈 中添加新条目。

    ¥router.replace(href: string, { scroll: boolean }): Perform a client-side navigation to the provided route without adding a new entry into the browser’s history stack.

  • router.refresh():刷新当前路由。向服务器发出新请求,重新获取数据请求,并重新渲染服务器组件。客户端将合并更新的 React Server 组件有效负载,而不会丢失未受影响的客户端 React(例如 useState)或浏览器状态(例如滚动位置)。

    ¥router.refresh(): Refresh the current route. Making a new request to the server, re-fetching data requests, and re-rendering Server Components. The client will merge the updated React Server Component payload without losing unaffected client-side React (e.g. useState) or browser state (e.g. scroll position).

  • router.prefetch(href: string)预请求 提供了更快的客户端转换的路由。

    ¥router.prefetch(href: string): Prefetch the provided route for faster client-side transitions.

  • router.back():导航回浏览器历史记录堆栈中的上一条路由。

    ¥router.back(): Navigate back to the previous route in the browser’s history stack.

  • router.forward():向前导航到浏览器历史记录堆栈中的下一页。

    ¥router.forward(): Navigate forwards to the next page in the browser’s history stack.

很高兴知道:

¥Good to know:

  • 你不得将不受信任或未经清理的 URL 发送到 router.pushrouter.replace,因为这可能会使你的网站面临跨站点脚本 (XSS) 漏洞。例如,发送到 router.pushrouter.replacejavascript: URL 将在你的页面上下文中执行。

    ¥You must not send untrusted or unsanitized URLs to router.push or router.replace, as this can open your site to cross-site scripting (XSS) vulnerabilities. For example, javascript: URLs sent to router.push or router.replace will be executed in the context of your page.

  • 当路由在视口中可见时,<Link> 组件会自动预取路由。

    ¥The <Link> component automatically prefetch routes as they become visible in the viewport.

  • 如果提取请求被缓存,refresh() 可能会重新产生相同的结果。其他动态 API(如 cookiesheaders)也可能更改响应。

    ¥refresh() could re-produce the same result if fetch requests are cached. Other Dynamic APIs like cookies and headers could also change the response.

next/router 迁移

¥Migrating from next/router

  • 使用 App Router 时,应从 next/navigation 而不是 next/router 导入 useRouter 钩子

    ¥The useRouter hook should be imported from next/navigation and not next/router when using the App Router

  • pathname 字符串已被删除并替换为 usePathname()

    ¥The pathname string has been removed and is replaced by usePathname()

  • query 对象已被删除并被 useSearchParams() 取代

    ¥The query object has been removed and is replaced by useSearchParams()

  • router.events 已被替换。见下文。

    ¥router.events has been replaced. See below.

查看完整的迁移指南

¥View the full migration guide.

示例

¥Examples

路由事件

¥Router events

你可以通过编写其他客户端组件钩子(例如 usePathnameuseSearchParams)来监听页面更改。

¥You can listen for page changes by composing other Client Component hooks like usePathname and useSearchParams.

'use client'

import { useEffect } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'

export function NavigationEvents() {
const pathname = usePathname()
const searchParams = useSearchParams()

useEffect(() => {
const url = `${pathname}?${searchParams}`
console.log(url)
// You can now use the current URL
// ...
}, [pathname, searchParams])

return '...'
}

可以将其导入到布局中。

¥Which can be imported into a layout.

import { Suspense } from 'react'
import { NavigationEvents } from './components/navigation-events'

export default function Layout({ children }) {
return (
<html lang="en">
<body>
{children}

<Suspense fallback={null}>
<NavigationEvents />
</Suspense>
</body>
</html>
)
}

很高兴知道:<NavigationEvents> 包含在 Suspense 边界 中,因为 useSearchParams() 导致客户端在 静态渲染 期间渲染到最近的 Suspense 边界。了解更多

¥Good to know: <NavigationEvents> is wrapped in a Suspense boundary becauseuseSearchParams() causes client-side rendering up to the closest Suspense boundary during static rendering. Learn more.

禁用滚动到顶部

¥Disabling scroll to top

默认情况下,当导航到新路由时,Next.js 将滚动到页面顶部。你可以通过将 scroll: false 传递到 router.push()router.replace() 来禁用此行为。

¥By default, Next.js will scroll to the top of the page when navigating to a new route. You can disable this behavior by passing scroll: false to router.push() or router.replace().

'use client'

import { useRouter } from 'next/navigation'

export default function Page() {
const router = useRouter()

return (
<button
type="button"
onClick={() => router.push('/dashboard', { scroll: false })}
>
Dashboard
</button>
)
}
'use client'

import { useRouter } from 'next/navigation'

export default function Page() {
const router = useRouter()

return (
<button
type="button"
onClick={() => router.push('/dashboard', { scroll: false })}
>
Dashboard
</button>
)
}

版本历史

¥Version History

版本变化
v13.0.0useRouter 是从 next/navigation 引入的。