useRouter
如果您想在應用程式中的任何函式元件內存取 router
物件,您可以使用 useRouter
Hook,請參考以下範例
import { useRouter } from 'next/router'
function ActiveLink({ children, href }) {
const router = useRouter()
const style = {
marginRight: 10,
color: router.asPath === href ? 'red' : 'black',
}
const handleClick = (e) => {
e.preventDefault()
router.push(href)
}
return (
<a href={href} onClick={handleClick} style={style}>
{children}
</a>
)
}
export default ActiveLink
useRouter
是一個 React Hook,這表示它不能與 Class 一起使用。您可以選擇使用 withRouter 或將您的 Class 包裝在函式元件中。
router
物件
以下是 useRouter
和 withRouter
傳回的 router
物件的定義
pathname
:String
- 當前路由檔案的路徑,接在/pages
之後。因此,不包含basePath
、locale
和尾部斜線 (trailingSlash: true
)。query
:Object
- 已解析為物件的查詢字串,包含動態路由參數。如果頁面未使用伺服器端渲染,則在預先渲染期間會是空物件。預設為{}
asPath
:String
- 瀏覽器中顯示的路徑,包含搜尋參數並遵循trailingSlash
設定。不包含basePath
和locale
。isFallback
:boolean
- 當前頁面是否處於 fallback 模式。basePath
:String
- 有效的 basePath(如果已啟用)。locale
:String
- 有效的 locale(如果已啟用)。locales
:String[]
- 所有支援的 locale(如果已啟用)。defaultLocale
:String
- 當前的預設 locale(如果已啟用)。domainLocales
:Array<{domain, defaultLocale, locales}>
- 任何已設定的網域 locale。isReady
:boolean
- router 欄位是否已在用戶端更新並準備好使用。應僅在useEffect
方法內部使用,而不適用於伺服器上的條件渲染。請參閱相關文件,以了解與自動靜態最佳化頁面的用例isPreview
:boolean
- 應用程式目前是否處於預覽模式。
如果頁面使用伺服器端渲染或自動靜態最佳化渲染,則使用
asPath
欄位可能會導致用戶端和伺服器之間的不匹配。在isReady
欄位為true
之前,請避免使用asPath
。
以下方法包含在 router
內部
router.push
處理用戶端轉換,此方法適用於 next/link
不足的情況。
router.push(url, as, options)
url
:UrlObject | String
- 要導航到的 URL(請參閱 Node.JS URL 模組文件 以取得UrlObject
屬性)。as
:UrlObject | String
- 將顯示在瀏覽器 URL 欄中的路徑的可選裝飾器。在 Next.js 9.5.3 之前,這用於動態路由。options
- 具有以下設定選項的可選物件scroll
- 可選的布林值,控制導航後捲動到頁面頂端。預設為true
shallow
:更新當前頁面的路徑,而無需重新執行getStaticProps
、getServerSideProps
或getInitialProps
。預設為false
locale
- 可選字串,表示新頁面的 locale
您不需要對外部 URL 使用
router.push
。window.location 更適合這些情況。
導航到 pages/about.js
,這是一個預定義的路由
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={() => router.push('/about')}>
Click me
</button>
)
}
導航到 pages/post/[pid].js
,這是一個動態路由
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={() => router.push('/post/abc')}>
Click me
</button>
)
}
將使用者重新導向到 pages/login.js
,適用於 身份驗證後面的頁面
import { useEffect } from 'react'
import { useRouter } from 'next/router'
// Here you would fetch and return the user
const useUser = () => ({ user: null, loading: false })
export default function Page() {
const { user, loading } = useUser()
const router = useRouter()
useEffect(() => {
if (!(user || loading)) {
router.push('/login')
}
}, [user, loading])
return <p>Redirecting...</p>
}
導航後重設狀態
在 Next.js 中導航到同一個頁面時,預設情況下,頁面的狀態不會重設,因為除非父元件已變更,否則 React 不會卸載。
import Link from 'next/link'
import { useState } from 'react'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
const [count, setCount] = useState(0)
return (
<div>
<h1>Page: {router.query.slug}</h1>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase count</button>
<Link href="/one">one</Link> <Link href="/two">two</Link>
</div>
)
}
在上述範例中,在 /one
和 /two
之間導航不會重設計數。useState
在渲染之間保持不變,因為頂層 React 元件 Page
是相同的。
如果您不想要此行為,則有幾種選項
-
手動確保使用
useEffect
更新每個狀態。在上述範例中,可能看起來像這樣useEffect(() => { setCount(0) }, [router.query.slug])
-
使用 React
key
來告訴 React 重新掛載元件。若要對所有頁面執行此操作,您可以使用自訂 Apppages/_app.jsimport { useRouter } from 'next/router' export default function MyApp({ Component, pageProps }) { const router = useRouter() return <Component key={router.asPath} {...pageProps} /> }
使用 URL 物件
您可以使用 URL 物件,就像您可以將其用於 next/link
一樣。適用於 url
和 as
參數
import { useRouter } from 'next/router'
export default function ReadMore({ post }) {
const router = useRouter()
return (
<button
type="button"
onClick={() => {
router.push({
pathname: '/post/[pid]',
query: { pid: post.id },
})
}}
>
Click here to read more
</button>
)
}
router.replace
與 next/link
中的 replace
屬性類似,router.replace
將防止將新的 URL 項目新增到 history
堆疊中。
router.replace(url, as, options)
router.replace
的 API 與router.push
的 API 完全相同。
請參考以下範例
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={() => router.replace('/home')}>
Click me
</button>
)
}
router.prefetch
預先載入頁面以加快用戶端轉換速度。此方法僅適用於沒有 next/link
的導航,因為 next/link
會自動處理頁面的預先載入。
這是一個僅限生產環境的功能。Next.js 不會在開發環境中預先載入頁面。
router.prefetch(url, as, options)
url
- 要預先載入的 URL,包含明確路由(例如/dashboard
)和動態路由(例如/product/[id]
)as
-url
的可選裝飾器。在 Next.js 9.5.3 之前,這用於預先載入動態路由。options
- 具有以下允許欄位的可選物件locale
- 允許提供與有效 locale 不同的 locale。如果為false
,則url
必須包含 locale,因為不會使用有效 locale。
假設您有一個登入頁面,並且在登入後,您將使用者重新導向到儀表板。對於這種情況,我們可以預先載入儀表板以實現更快的轉換,如下列範例所示
import { useCallback, useEffect } from 'react'
import { useRouter } from 'next/router'
export default function Login() {
const router = useRouter()
const handleSubmit = useCallback((e) => {
e.preventDefault()
fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
/* Form data */
}),
}).then((res) => {
// Do a fast client-side transition to the already prefetched dashboard page
if (res.ok) router.push('/dashboard')
})
}, [])
useEffect(() => {
// Prefetch the dashboard page
router.prefetch('/dashboard')
}, [router])
return (
<form onSubmit={handleSubmit}>
{/* Form fields */}
<button type="submit">Login</button>
</form>
)
}
router.beforePopState
在某些情況下(例如,如果使用自訂伺服器),您可能希望監聽 popstate 並在 router 對其執行操作之前執行某些操作。
router.beforePopState(cb)
cb
- 在傳入的popstate
事件上執行的函式。該函式接收事件的狀態作為具有以下屬性的物件url
:String
- 新狀態的路由。這通常是page
的名稱as
:String
- 將在瀏覽器中顯示的 URLoptions
:Object
- 由 router.push 傳送的其他選項
如果 cb
傳回 false
,則 Next.js router 將不會處理 popstate
,並且在這種情況下您將負責處理它。請參閱停用檔案系統路由。
您可以使用 beforePopState
來操作請求,或強制執行 SSR 重新整理,如下列範例所示
import { useEffect } from 'react'
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
useEffect(() => {
router.beforePopState(({ url, as, options }) => {
// I only want to allow these two routes!
if (as !== '/' && as !== '/other') {
// Have SSR render bad routes as a 404.
window.location.href = as
return false
}
return true
})
}, [router])
return <p>Welcome to the page</p>
}
router.back
在歷史記錄中返回。相當於按一下瀏覽器的返回按鈕。它會執行 window.history.back()
。
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={() => router.back()}>
Click here to go back
</button>
)
}
router.reload
重新載入當前 URL。相當於按一下瀏覽器的重新整理按鈕。它會執行 window.location.reload()
。
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={() => router.reload()}>
Click here to reload
</button>
)
}
router.events
您可以監聽 Next.js Router 內發生的不同事件。以下是支援的事件清單
routeChangeStart(url, { shallow })
- 在路由開始變更時觸發routeChangeComplete(url, { shallow })
- 在路由完全變更時觸發routeChangeError(err, url, { shallow })
- 在變更路由時發生錯誤或路由載入取消時觸發err.cancelled
- 指示導航是否已取消
beforeHistoryChange(url, { shallow })
- 在變更瀏覽器的歷史記錄之前觸發hashChangeStart(url, { shallow })
- 在雜湊值將變更但頁面不變更時觸發hashChangeComplete(url, { shallow })
- 在雜湊值已變更但頁面不變更時觸發
要知道的好處:此處的
url
是瀏覽器中顯示的 URL,包含basePath
。
例如,若要監聽 router 事件 routeChangeStart
,請開啟或建立 pages/_app.js
並訂閱該事件,如下所示
import { useEffect } from 'react'
import { useRouter } from 'next/router'
export default function MyApp({ Component, pageProps }) {
const router = useRouter()
useEffect(() => {
const handleRouteChange = (url, { shallow }) => {
console.log(
`App is changing to ${url} ${
shallow ? 'with' : 'without'
} shallow routing`
)
}
router.events.on('routeChangeStart', handleRouteChange)
// If the component is unmounted, unsubscribe
// from the event with the `off` method:
return () => {
router.events.off('routeChangeStart', handleRouteChange)
}
}, [router])
return <Component {...pageProps} />
}
我們在此範例中使用自訂 App (
pages/_app.js
) 來訂閱事件,因為它在頁面導航時不會卸載,但您可以在應用程式中的任何元件上訂閱 router 事件。
Router 事件應在元件掛載時註冊 (useEffect 或 componentDidMount / componentWillUnmount) 或在事件發生時強制註冊。
如果路由載入已取消(例如,透過快速連續按一下兩個連結),則會觸發 routeChangeError
。並且傳遞的 err
將包含一個 cancelled
屬性,該屬性設定為 true
,如下列範例所示
import { useEffect } from 'react'
import { useRouter } from 'next/router'
export default function MyApp({ Component, pageProps }) {
const router = useRouter()
useEffect(() => {
const handleRouteChangeError = (err, url) => {
if (err.cancelled) {
console.log(`Route to ${url} was cancelled!`)
}
}
router.events.on('routeChangeError', handleRouteChangeError)
// If the component is unmounted, unsubscribe
// from the event with the `off` method:
return () => {
router.events.off('routeChangeError', handleRouteChangeError)
}
}, [router])
return <Component {...pageProps} />
}
next/compat/router
匯出
這與 useRouter
Hook 相同,但可以在 app
和 pages
目錄中使用。
它與 next/router
的不同之處在於,當未掛載頁面 router 時,它不會擲回錯誤,而是具有 NextRouter | null
的傳回類型。這允許開發人員在轉換到 app
router 時,轉換元件以支援在 app
和 pages
中執行。
先前看起來像這樣的元件
import { useRouter } from 'next/router'
const MyComponent = () => {
const { isReady, query } = useRouter()
// ...
}
當轉換為 next/compat/router
時會發生錯誤,因為無法解構 null
。相反地,開發人員將能夠利用新的 Hook
import { useEffect } from 'react'
import { useRouter } from 'next/compat/router'
import { useSearchParams } from 'next/navigation'
const MyComponent = () => {
const router = useRouter() // may be null or a NextRouter instance
const searchParams = useSearchParams()
useEffect(() => {
if (router && !router.isReady) {
return
}
// In `app/`, searchParams will be ready immediately with the values, in
// `pages/` it will be available after the router is ready.
const search = searchParams.get('search')
// ...
}, [router, searchParams])
// ...
}
此元件現在將在 pages
和 app
目錄中運作。當元件不再在 pages
中使用時,您可以移除對 Compat Router 的參考
import { useSearchParams } from 'next/navigation'
const MyComponent = () => {
const searchParams = useSearchParams()
// As this component is only used in `app/`, the compat router can be removed.
const search = searchParams.get('search')
// ...
}
在頁面中 Next.js 內容之外使用 useRouter
另一個特定的用例是在 Next.js 應用程式內容之外渲染元件時,例如在 pages
目錄上的 getServerSideProps
內。在這種情況下,可以使用 Compat Router 來避免錯誤
import { renderToString } from 'react-dom/server'
import { useRouter } from 'next/compat/router'
const MyComponent = () => {
const router = useRouter() // may be null or a NextRouter instance
// ...
}
export async function getServerSideProps() {
const renderedComponent = renderToString(<MyComponent />)
return {
props: {
renderedComponent,
},
}
}
潛在的 ESLint 錯誤
router
物件上可存取的某些方法會傳回 Promise。如果您已啟用 ESLint 規則 no-floating-promises,請考慮全域停用它,或針對受影響的行停用它。
如果您的應用程式需要此規則,您應該 void
Promise – 或使用 async
函式、await
Promise,然後 void 函式呼叫。當方法是從 onClick
處理常式內部呼叫時,這不適用。
受影響的方法是
router.push
router.replace
router.prefetch
潛在的解決方案
import { useEffect } from 'react'
import { useRouter } from 'next/router'
// Here you would fetch and return the user
const useUser = () => ({ user: null, loading: false })
export default function Page() {
const { user, loading } = useUser()
const router = useRouter()
useEffect(() => {
// disable the linting on the next line - This is the cleanest solution
// eslint-disable-next-line no-floating-promises
router.push('/login')
// void the Promise returned by router.push
if (!(user || loading)) {
void router.push('/login')
}
// or use an async function, await the Promise, then void the function call
async function handleRouteChange() {
if (!(user || loading)) {
await router.push('/login')
}
}
void handleRouteChange()
}, [user, loading])
return <p>Redirecting...</p>
}
withRouter
如果 useRouter
不是最適合您的選擇,withRouter
也可以將相同的 router
物件 新增到任何元件。
用法
import { withRouter } from 'next/router'
function Page({ router }) {
return <p>{router.pathname}</p>
}
export default withRouter(Page)
TypeScript
若要將 Class 元件與 withRouter
一起使用,元件需要接受 router prop
import React from 'react'
import { withRouter, NextRouter } from 'next/router'
interface WithRouterProps {
router: NextRouter
}
interface MyComponentProps extends WithRouterProps {}
class MyComponent extends React.Component<MyComponentProps> {
render() {
return <p>{this.props.router.pathname}</p>
}
}
export default withRouter(MyComponent)
這個有幫助嗎?