路由匹配遵循一致且可預測的模式。本指南將解釋路由樹的匹配方式。
當 TanStack Router 處理您的路由樹時,所有路由會自動排序以優先匹配最具體的路由。這意味著無論路由樹的定義順序為何,路由始終會按照以下順序排序:
考慮以下虛擬路由樹:
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 的匹配過程:
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
- *
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
✅ *
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.