拦截路由
拦截路由允许您从应用程序的其他部分加载路由到当前布局中。当您希望显示路由的内容而不让用户切换到不同的上下文时,这种路由范式非常有用。
例如,当在 Feed 中点击照片时,您可以将照片显示在模态框中,覆盖 Feed。在这种情况下,Next.js 会拦截 /photo/123
路由,屏蔽 URL,并将其覆盖在 /feed
上。


但是,当通过点击可共享的 URL 或刷新页面导航到照片时,应该渲染整个照片页面,而不是模态框。不应发生任何路由拦截。


约定
拦截路由可以使用 (..)
约定来定义,这与相对路径约定 ../
类似,但用于段。
您可以使用
(.)
匹配**同一级别**上的段(..)
匹配**上一级**的段(..)(..)
匹配**上两级**的段(...)
匹配来自**根**app
目录的段
例如,您可以通过创建 (..)photo
目录来拦截 feed
段中的 photo
段。


请注意,
(..)
约定基于路由段,而不是文件系统。
示例
模态框
拦截路由可以与并行路由一起使用来创建模态框。这使您可以解决构建模态框时常见的挑战,例如
- 使模态框内容**可以通过 URL 共享**。
- 页面刷新时**保留上下文**,而不是关闭模态框。
- **在向后导航时关闭模态框**,而不是转到上一个路由。
- 在向前导航时重新打开模态框.
考虑以下 UI 模式,用户可以在其中使用客户端导航从图库打开照片模态框,或从可共享的 URL 直接导航到照片页面


在上面的示例中,photo
段的路径可以使用 (..)
匹配器,因为 @modal
是一个插槽,**而不是**段。这意味着 photo
路由仅比文件系统高一级,尽管它在文件系统中高两级。
需要了解
- 其他示例可能包括在顶部导航栏中打开登录模态框,同时还具有专用的
/login
页面,或在侧边模态框中打开购物车。
这有帮助吗?