P粉4589136552023-08-26 17:20:32
是的,绝对可以。每个Routes
组件都管理着自己可以匹配的路由的“范围”。例如,如果当前的URL路径是"/messages/loremipsum"
,根Routes
组件会匹配"/messages/*"
,并正确渲染MessageRoutes
组件。然后,MessageRoutes
组件的Routes
组件会继续匹配下一个路径段。由于没有"*/loremipsum"
的路由路径,您需要另一个“catch-all”路由来处理这个。
问题在于Routes
组件不知道它的任何路由可能渲染的后代路由。
示例:
import { Route, Routes } from "react-router-dom"; import NotFound from "../pages/NotFound"; import MessageRoutes from "../features/messages/routes/MessageRoutes"; import Home from "../pages/Home"; export default function AppRoutes() { return ( <Routes> <Route path="/" element={<Home />} /> <Route path="/messages/*" element={<MessageRoutes />} /> <Route path="*" element={<NotFound />} /> </Routes> ); }
import { Route, Routes } from "react-router-dom"; import ProtectedRoutes from "../../../routes/ProtectedRoutes"; import MessageOverview from "../pages/MessageOverview"; import NewMessage from "../pages/NewMessage"; import NotFound from "../pages/NotFound"; export default function MessageRoutes() { return ( <Routes> <Route element={<ProtectedRoutes />}> <Route path="/" element={<MessageOverview />} /> <Route path="/new" element={<NewMessage />} /> <Route path="*" element={<NotFound />} /> </Route> </Routes> ); }
如果您想要一个单独的“catch-all”路由,那么您需要一个单独的路由配置。
示例:
import { Route, Routes } from "react-router-dom"; import MessageOverview from "../pages/MessageOverview"; import NewMessage from "../pages/NewMessage"; import NotFound from "../pages/NotFound"; import Home from "../pages/Home"; export default function AppRoutes() { return ( <Routes> <Route path="/" element={<Home />} /> <Route element={<ProtectedRoutes />}> <Route path="/messages"> <Route index element={<MessageOverview />} /> <Route path="new" element={<NewMessage />} /> </Route> </Route> <Route path="*" element={<NotFound />} /> </Routes> ); }
现在,当URL路径是"/messages/loremipsum"
时,这个Routes
组件知道它正在渲染的嵌套路由,并且可以正确匹配并渲染NotFound
。