跳到主要内容

定义路由与嵌套布局

如何定义 Routes?​

  • 匹配集合: Routes 按当前 location 匹配 Route;
  • path: 描述路径; element: 描述对应界面;
  • 动态片段: :id 表示路径参数, * 可匹配未消费路径, 具体值可在路由组件中读取;
import { Routes, Route } from "react-router";

function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="users/:id" element={<User />} />
<Route path="*" element={<NotFound />} />
</Routes>
);
}

嵌套子路由怎样进入父布局?​

  • Outlet: 父布局在展示子路由的位置渲染 Outlet;
  • 否则: 子路由匹配了也没有可见插槽;
  • 相对路径: 子 path 相对父路径拼成完整 URL;
  • index: 表示父路径本身的默认内容, 不再有自己的 path;
import { Outlet } from "react-router";

function DashboardLayout() {
return (
<main>
<h1>控制台</h1>
<Outlet />
</main>
);
}

const routes = (
<Route path="dashboard" element={<DashboardLayout />}>
<Route index element={<Overview />} />
<Route path="messages" element={<Messages />} />
</Route>
);

如何用对象表达相同的路由结构?​

  • useRoutes: 接收路由对象数组并返回匹配的元素, 仍需要位于 Router 上下文中;
  • 结构对应: path、element、children 与 JSX Route 表达同一层级关系;
  • 取舍: 选项目更易维护的形式;
function RouteContent() {
return useRoutes([
{ path: "/", element: <Home /> },
{ path: "/users/:id", element: <User /> },
{ path: "*", element: <NotFound /> },
]);
}