P粉4589136552023-08-26 17:20:32
Yes, absolutely. Each Routes
component manages the "scope" of routes it can match. For example, if the current URL path is "/messages/loremipsum"
, the root Routes
component will match "/messages/*"
and render ## correctly #MessageRoutesComponent. Then, the
Routes component of the
MessageRoutes component will continue to match the next path segment. Since there is no routing path for
"*/loremipsum", you need another "catch-all" route to handle this.
Routes component is not aware of the
descendant routes that any of its routes may render.
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> ); }If you want a separate "catch-all" route, then you need a separate route configuration.
Example:
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> ); }Now, when the URL path is
"/messages/loremipsum",
the Routes component knows the
embed it is rendering Set routing, and can correctly match and render NotFound.