Concepts

嵌套路由

编辑此页面

嵌套路由是在应用程序中创建路由层次结构的一种方式。这对于创建跨多个页面保持一致的布局,或者创建相互关联的页面之间的关系非常有用。

在 Solid Router 中,以下两种路由定义具有相同的结果:

<Route path="/users/:id" component={User} />
// is equivalent to
<Route path="/users">
<Route path="/:id" component={User} />
</Route>

In both cases, the User component will render when the URL is /users/:id. The difference, however, is that in the first case, /users/:id is the only route, and in the second case, /users is also a route.

在这两种情况下,当 URL/users/:id 时,User 组件都会渲染。然而,区别在于第一种情况下,/users/:id 是唯一的路由,而在第二种情况下,/users 也是一个路由。

注意:访问基于配置的嵌套章节,了解更多关于使用基于配置的方法嵌套路由的信息。


限制

在嵌套路由时,只有最内层的 Route 组件会成为独立的路由。例如,如果你要嵌套一个路由,即使父路由也被指定并提供了组件,也只有最内层的路由会成为独立的路由:

<Route path="/users" component={Users}>
<Route path="/:id" component={User} />
</Route>

要使父路由成为独立的路由,必须单独指定它。这可以通过同时明确定义父路由和嵌套路由来实现:

<Route path="/users" component={Users} />
<Route path="/users/:id" component={User} />

实现相同结果的另一种方式是嵌套路由,通过使用空路径显式定义父路由,然后指定嵌套路由:

<Route path="/users">
<Route path="/" component={Users} />
<Route path="/:id" component={User} />
</Route>

在这两种情况下,当 URL 为 /users 时,Users 组件将会渲染,当 URL 为 /users/:id 时,User 组件将会渲染。


基于配置的嵌套

在使用基于配置的路由时,可以通过将路由定义传递到父路由定义对象的 children 属性来实现嵌套:

import { render } from "solid-js/web";
import { Router } from "@solidjs/router";
const routes = {
path: "/",
component: lazy(() => import("/routes/index.js")),
children: [
{
path: "/users",
component: lazy(() => import("/routes/users.js")),
children: [
{
path: "/:id",
component: lazy(() => import("/routes/user.js")),
},
],
},
],
};
render(() => <Router>{routes}</Router>, document.getElementById("app"));

在这个例子中,当你导航到 /users/:id 时,User 组件将会渲染。同样,当你导航到 /users 时,Users 组件将会渲染。

报告此页面问题