路由匹配遵循一致且可预测的模式。本指南将解释路由树是如何进行匹配的。
当 TanStack Router 处理你的路由树时,你的所有路由都会被自动排序,以便优先匹配**最具体(most specific)**的路由。这意味着无论你定义路由树的顺序如何,路由总是会按照以下顺序进行排序:
-
索引路由 (Index Route)
-
静态路由 (Static Routes)(从最具体到最不具体)
-
动态路由 (Dynamic Routes)(从最长到最短)
-
Splat/通配符路由 (Splat/Wildcard Routes)
考虑以下的伪路由树(定义时的顺序):
bash
Root
- blog
- $postId
- /
- new
- /
- *
- about
- about/us
排序后,这个路由树将变为:
scss
Root
- / (根索引路由,优先级最高)
- about/us (最具体的静态路由)
- about (较短的静态路由)
- blog (静态路由)
- / (Blog 的索引路由)
- new (Blog 下的静态路由)
- $postId (Blog 下的动态路由)
- * (Splat/通配符,优先级最低)
这个最终顺序代表了基于特异性(specificity)进行路由匹配的顺序。
使用上述排序后的路由树,让我们来看看几个不同 URL 的匹配过程:
-
/blogbashRoot ❌ / ❌ about/us ❌ about ⏩ blog ✅ / - new - $postId - * -
/blog/my-postbashRoot ❌ / ❌ about/us ❌ about ⏩ blog ❌ / ❌ new ✅ $postId - * -
/markdownRoot ✅ / - about/us - about - blog - / - new - $postId - * -
/not-a-routemarkdownRoot ❌ / ❌ about/us ❌ about ❌ blog - / - new - $postId ✅ *