框架
版本

路由匹配

路由匹配遵循一致且可预测的模式。本指南将解释路由树是如何匹配的。

当 TanStack Router 处理您的路由树时,您的所有路由都会自动排序,以首先匹配最具体的路由。这意味着无论您的路由树是如何定义的顺序,路由将始终按此顺序排序

  • 索引路由
  • 静态路由(从最具体到最不具体)
  • 动态路由(从最长到最短)
  • Splat/通配符路由

考虑以下伪路由树

Root
  - blog
    - $postId
    - /
    - new
  - /
  - *
  - about
  - about/us
Root
  - blog
    - $postId
    - /
    - new
  - /
  - *
  - about
  - about/us

排序后,此路由树将变为

Root
  - /
  - about/us
  - about
  - blog
    - /
    - new
    - $postId
  - *
Root
  - /
  - about/us
  - about
  - blog
    - /
    - new
    - $postId
  - *

此最终顺序表示路由将根据特异性进行匹配的顺序。

使用该路由树,让我们跟踪一些不同 URL 的匹配过程

  • /blog
    Root
      ❌ /
      ❌ about/us
      ❌ about
      ⏩ blog
        ✅ /
        - new
        - $postId
      - *
    
    Root
      ❌ /
      ❌ about/us
      ❌ about
      ⏩ blog
        ✅ /
        - new
        - $postId
      - *
    
  • /blog/my-post
    Root
      ❌ /
      ❌ about/us
      ❌ about
      ⏩ blog
        ❌ /
        ❌ new
        ✅ $postId
      - *
    
    Root
      ❌ /
      ❌ about/us
      ❌ about
      ⏩ blog
        ❌ /
        ❌ new
        ✅ $postId
      - *
    
  • /
    Root
      ✅ /
      - about/us
      - about
      - blog
        - /
        - new
        - $postId
      - *
    
    Root
      ✅ /
      - about/us
      - about
      - blog
        - /
        - new
        - $postId
      - *
    
  • /not-a-route
    Root
      ❌ /
      ❌ about/us
      ❌ about
      ❌ blog
        - /
        - new
        - $postId
      ✅ *
    
    Root
      ❌ /
      ❌ about/us
      ❌ about
      ❌ blog
        - /
        - new
        - $postId
      ✅ *
    
订阅 Bytes

您的每周 JavaScript 新闻。每周一免费发送给超过 100,000 名开发者。

Bytes

无垃圾邮件。随时取消订阅。