全书目录

第五篇:Next.js 完全指南 —— 商业综合体宇宙

第三章:路由 —— 每一层楼、每一家店,都靠文件夹落位

1 分钟 355 字 第 114 / 962 个阅读单元

在 App Router 里,路由就是文件系统映射

tsx
// app/page.tsx
export default function HomePage() {
  return <h1>商业综合体首页</h1>;
}

这对应 /

tsx
// app/dashboard/page.tsx
export default function DashboardPage() {
  return <h1>运营后台</h1>;
}

这对应 /dashboard

#1. layout.tsx —— 公共走廊和天花板

layout.tsx 负责包住同一路由段下的所有页面,就像公共走廊、统一招牌、天花板、侧边导航。

tsx
// app/layout.tsx
import type { ReactNode } from 'react';

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="zh-CN">
      <body>
        <header>软件城市商业综合体</header>
        <main>{children}</main>
      </body>
    </html>
  );
}
tsx
// app/dashboard/layout.tsx
import type { ReactNode } from 'react';

export default function DashboardLayout({ children }: { children: ReactNode }) {
  return (
    <section>
      <aside>侧边导航</aside>
      <div>{children}</div>
    </section>
  );
}

这意味着:

text
根 layout
└── dashboard layout
    └── dashboard page
#2. 动态路由 —— 可变店铺号
tsx
// app/products/[slug]/page.tsx
export default async function ProductPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;

  return <h1>商品编号:{slug}</h1>;
}

这里最容易写旧:

  • 到 2026-03-28 的官方文档写法里,paramssearchParams 都按 Promise 来处理。
  • 也就是说,在 page.tsx 里你应该准备好 await paramsawait searchParams
tsx
// app/search/page.tsx
export default async function SearchPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string }>;
}) {
  const { q = '' } = await searchParams;
  return <h1>搜索:{q}</h1>;
}
tsx
import Link from 'next/link';

export default function Nav() {
  return (
    <nav>
      <Link href="/">首页</Link>
      <Link href="/products">商品街</Link>
      <Link href="/dashboard">运营后台</Link>
    </nav>
  );
}

Link 不是普通 <a> 的简单替代。它是 Next.js 导航系统的一部分,会配合路由、预取和客户端切换一起工作。