React Router 子層级的路由
首先
查找出的一个解决方案
在 App.tsx 中调用 Router.tsx
import "./styles.css";
import { ChakraProvider } from "@chakra-ui/react";
import { BrowserRouter } from "react-router-dom";
import { Router } from "./router/Router";
import theme from "./theme/theme";
export default function App() {
return (
<ChakraProvider theme={theme}>
<BrowserRouter>
<Router />
</BrowserRouter>
</ChakraProvider>
);
}
・/主页
・/主页/用户管理
・/主页/设置
当想要转到子层时
import { FC, memo } from "react";
import { Routes, Route } from "react-router-dom";
import { Login } from "../components/pages/Login";
import { homeRoutes } from "./HomeRoutes";
export const Router: FC = memo(() => {
return (
<Routes>
<Route path="/" element={<Login />} />
<Route path="home" element={<Home />}>
<Route path="user_management" element={<UserManagement />} />
<Route path="setting" element={<Setting />} />
</Route>
</Routes>
);
});
在Outlet部分,嵌套了与UserManagement和Setting相关的组件。
import { FC, memo } from "react";
import { Outlet } from "react-router-dom";
export const Home: FC = memo(() => {
return (
<div>
<p>HOME</p>
<Outlet />
</div>
);
});
然而,我想做的事是在子层面上“转变”。
乍一看,觉得外观不太好看。
将【解决】路由路径分割到另一个文件中,并通过map展开。
在一个单独的文件中管理根路径。
import { Home } from "../components/pages/Home";
import { Setting } from "../components/pages/Setting";
import { UserManagement } from "../components/pages/UserManagement";
export const homeRoutes = [
{
path: "",
children: <Home />
},
{
path: "user_management",
children: <UserManagement />
},
{
path: "setting",
children: <Setting />
}
];
只需调用HomeRoutes并在map()中展开每个定义的路由。
在HomeRoutes.tsx中,只需注意路径的指定,就可以实现这一点。
import { homeRoutes } from "./HomeRoutes";
<Routes>
<Route path="/" element={<Login />} />
<Route path="/home">
{homeRoutes.map((route) => (
<Route key={route.path} path={route.path} element={route.children} />
))}
</Route>
</Routes>
最后
如果有什么意见,请您指教。