共享路由

了解如何使用 Expo Router 定义共享路由或使用数组以不同布局多次使用同一路由。


要匹配具有不同布局的相同 URL,请使用具有重叠子路由的 groups。这种模式在原生应用中非常常见。例如,在 X 应用中,个人资料可以在每个标签页中查看(如首页、搜索和个人资料)。然而,访问此路由只需要一个 URL。

🌐 To match the same URL with different layouts, use groups with overlapping child routes. This pattern is very common in native apps. For example, in the X app, a profile can be viewed in every tab (such as home, search, and profile). However, there is only one URL that is required to access this route.

在下面的示例中,app/_layout.tsx 是标签栏,每个路由都有自己的标题。app/(profile)/[user].tsx 路由在每个标签之间共享。

🌐 In the example below, app/_layout.tsx is the tab bar and each route has its own header. The app/(profile)/[user].tsx route is shared between each tab.

app
_layout.tsx
(home)
  _layout.tsx
  [user].tsx
(search)
  _layout.tsx
  [user].tsx
(profile)
  _layout.tsx
  [user].tsx

当重新加载页面时,会显示第一个按字母顺序匹配的项。

共享路由可以通过在路由中包含组名直接导航。例如,/(search)/baconbrix 会在“搜索”布局中导航到 /baconbrix

🌐 Shared routes can be navigated directly by including the group name in the route. For example, /(search)/baconbrix navigates to /baconbrix in the "search" layout.

数组

🌐 Arrays

数组语法是一种高级概念,它在原生应用开发中独具特色。

与其多次使用不同的布局定义相同的路由,不如使用数组语法 (,) 来复制一个组的子路由。例如,app/(home,search)/[user].tsx —— 在内存中创建 app/(home)/[user].tsxapp/(search)/[user].tsx

🌐 Instead of defining the same route multiple times with different layouts, use the array syntax (,) to duplicate the children of a group. For example, app/(home,search)/[user].tsx — creates app/(home)/[user].tsx and app/(search)/[user].tsx in memory.

要区分这两条路由,请使用布局的 segment 属性:

🌐 To distinguish between the two routes use a layout's segment prop:

app/(home,search)/_layout.tsx
export default function DynamicLayout({ segment }) { if (segment === '(search)') { return <SearchStack />; } return <Stack />; }

要启用数组语法,请在动态布局中使用 unstable_settings 对象为每个组指定 initialRouteName

🌐 To enable the array syntax, specify the initialRouteName for each group using unstable_settings object in the dynamic layout:

app/(home,search)/_layout.tsx
export const unstable_settings = { initialRouteName: 'home', search: { initialRouteName: 'search', }, }; export default function DynamicLayout({ segment }) { %%placeholder-start%% ... %%placeholder-end%% }

在上述示例中,home 路由是 home 组和应用的默认路由。search 路由是 search 组的默认路由。

🌐 In the above example, the home route is the default route for the home group and the app. The search route is the default route for the search group.

关键点

🌐 Key points

  • 你只能为当前导航器提供组。
  • 使用数组语法时,如果有两个分组(例如 (one)/(two)),则只有最后一个分组的片段用于匹配路由。
  • 如果至少有两个 initialRouteNames 组,但未提供默认 initialRouteName,则使用第一个组的 initialRouteName