框架
版本

路由树

TanStack Router 使用嵌套路由树将 URL 与要渲染的正确组件树匹配。

要构建路由树,TanStack Router 支持:

两种方法都支持完全相同的核心功能,但基于文件的路由需要更少的代码来获得相同或更好的结果。因此,基于文件的路由是配置 TanStack Router 的首选和推荐方式。大部分文档都是从基于文件的路由的角度编写的。

路由树

嵌套路由是一个强大的概念,允许您使用 URL 来渲染嵌套的组件树。例如,给定 URL /blog/posts/123,您可以创建如下所示的路由层次结构:

tsx
├── blog
│   ├── posts
│   │   ├── $postId
├── blog
│   ├── posts
│   │   ├── $postId

并渲染如下所示的组件树:

tsx
<Blog>
  <Posts>
    <Post postId="123" />
  </Posts>
</Blog>
<Blog>
  <Posts>
    <Post postId="123" />
  </Posts>
</Blog>

让我们采用这个概念并将其扩展到更大的站点结构,但现在使用文件名:

/routes
├── __root.tsx
├── index.tsx
├── about.tsx
├── posts/
│   ├── index.tsx
│   ├── $postId.tsx
├── posts.$postId.edit.tsx
├── settings/
│   ├── profile.tsx
│   ├── notifications.tsx
├── _pathlessLayout/
│   ├── route-a.tsx
├── ├── route-b.tsx
├── files/
│   ├── $.tsx
/routes
├── __root.tsx
├── index.tsx
├── about.tsx
├── posts/
│   ├── index.tsx
│   ├── $postId.tsx
├── posts.$postId.edit.tsx
├── settings/
│   ├── profile.tsx
│   ├── notifications.tsx
├── _pathlessLayout/
│   ├── route-a.tsx
├── ├── route-b.tsx
├── files/
│   ├── $.tsx

上面是一个可以与 TanStack Router 一起使用的有效路由树配置!基于文件的路由有很多功能和约定需要解释,所以让我们稍微分解一下。

路由树配置

路由树可以通过几种不同的方式进行配置:

请务必查看上面每种路由树类型的完整文档链接,或者直接进入下一部分开始使用基于文件的路由。