路由树与 file-based routing 心智模型
这一块想让你脑子里有一棵“路由树”,能用它描述典型应用结构,比如 /app → /app/posts → /app/posts/$postId。
1. 路由是树,不是扁平的 URL 列表
在 TanStack Router 里,路由本质上是一个嵌套的树,父路由负责 layout / shell,子路由负责具体页面内容(route trees 文档)。
用一个典型博客应用来感受一下:
ts// app/routes/__root.tsx
export const Route = createRootRoute({
component: RootLayout,
})
// app/routes/app.tsx
export const Route = createRoute({
getParentRoute: () => rootRoute,
path: 'app',
component: AppLayout,
})
// app/routes/app.posts.tsx
export const Route = createRoute({
getParentRoute: () => appRoute,
path: 'posts',
component: PostsLayout,
})
// app/routes/app.posts.$postId.tsx
export const Route = createRoute({
getParentRoute: () => appPostsRoute,
path: '$postId',
component: PostDetailPage,
})
这四个路由实际形成的是这样一棵树:
Rendering diagram…
路径展开过程是:
root→/app→/appposts→/app/posts$postId→/app/posts/123(例如)
如果你用的是 file-based routing(见 file-based routing 文档),文件名就直接映射到这棵树:
| 路由文件名 | 路由 path 片段 | 完整示例路径 | 直观含义 |
|---|---|---|---|
__root.tsx | / | / | 根 layout |
app.tsx | app | /app | 应用主区 |
app.posts.tsx | posts | /app/posts | 帖子列表 layout |
app.posts.$postId.tsx | $postId | /app/posts/abc123 | 某一篇帖子详情 |
能用树的方式口头描述结构,就是:从根一路往下念:
根路由
/提供整体框架,下面有/app,/app下面有/app/posts,而/app/posts下面再有带动态参数的/app/posts/$postId。
2. layout 与嵌套路由是怎么协作的
父 route 的 component 里通常写 layout,并通过 Outlet 渲染子 route(见 outlets 文档):
// app/routes/app.tsx
import { Outlet } from '@tanstack/react-router'
function AppLayout() {
return (
<div>
<Sidebar />
<main>
<Outlet /> {/* 这里渲染 /app 的子路由 */}
</main>
</div>
)
}
export const Route = createRoute({
getParentRoute: () => rootRoute,
path: 'app',
component: AppLayout,
})
当用户访问 /app/posts/123 时,渲染链条大致是:
Rendering diagram…
你会看到多个 layout 嵌在一起,但 URL 只是一条路径 /app/posts/123。
1 / 5