🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 概述 **index router** * `pages/index.js`→`/` * `pages/blog/index.js`→`/blog` **嵌套路由** * `pages/blog/first-post.js`→`/blog/first-post` * `pages/dashboard/settings/username.js`→`/dashboard/settings/username` ## 动态路由 `app/blog/[slug]/page.js` ``` export default async function Page({ params, }: { params: Promise<{ slug: string }> }) { const slug = (await params).slug return <div>My Post: {slug}</div> } ``` | Route | Example URL | `params` | | --- | --- | --- | | `app/blog/[slug]/page.js` | `/blog/a` | `{ slug: 'a' }` | | `app/blog/[slug]/page.js` | `/blog/b` | `{ slug: 'b' }` | | `app/blog/[slug]/page.js` | `/blog/c` | `{ slug: 'c' }` | **多个匹配** `app/shop/[...slug]/page.js` | Route | Example URL | `params` | | --- | --- | --- | | `app/shop/[...slug]/page.js` | `/shop/a` | `{ slug: ['a'] }` | | `app/shop/[...slug]/page.js` | `/shop/a/b` | `{ slug: ['a', 'b'] }` | | `app/shop/[...slug]/page.js` | `/shop/a/b/c` | `{ slug: ['a', 'b', 'c'] }` | ## 方法跳转 客户端组件 ``` import router from "next/router"; export default function IndexPage() { return ( <> <h1>Hello World!</h1> <button onClick={() => { router.push('/idcpj/settings') }}>demo</button> </> ); } ``` 存在服务端组件`Server Component` ``` 'use client' import { useRouter } from "next/navigation"; export default function IndexPage() { const router = useRouter() return ( <> <h1>Hello World!</h1> <button onClick={() => { router.push('/idcpj/settings') }}>demo</button> </> ); } ``` ## `next/router` 和 `next navigation` 区别主要区别: 使用场景: ``` next/router: Pages Router(pages/目录) next/navigation: App Router(app/目录) ``` API 差异: ``` App Router 移除了 query 和 pathname 属性 App Router 新增了 refresh() 和 forward() 方法 ``` 获取路由信息 ``` // Pages Router import { useRouter } from 'next/router' const router = useRouter() const { query, pathname } = router // App Router import { useRouter, useSearchParams, usePathname } from 'next/navigation' const router = useRouter() const searchParams = useSearchParams() const pathname = usePathname() ``` ## redirect 再 server 端可以使用 这个函数用于跳转 ``` import { redirect } from 'next/navigation' async function fetchTeam(id: string) { const res = await fetch('https://...') if (!res.ok) return undefined return res.json() } export default async function Profile({ params }: { params: { id: string } }) { const team = await fetchTeam(params.id) if (!team) { redirect('/login') } // ... } ```