我正在尝试在 `react-router-dom v6 中组织路由。以下是我的流程:
根应用组件
function AppComponent() { return <AppRoute />; }
AppRoute.js(基本路线)
const AppRoute = () => { return ( <> <GuestRoute path="/login" component={Login} /> </> ); };
客人路线
const GuestRoute = ({ component: Component, ...rest }) => { return ( <GuestLayout> <Routes> <Route {...rest} element={<Component />} /> </Routes> </GuestLayout> ); };
客人布局
const GuestLayout = ({ children, ...rest }) => { return ( <div> {children} </div> ); };
但是,当我转到 时/login,它并没有破坏页面,但它仍然显示 的警告No routes matched location "/login"。我正在使用react-router-dom v6
/login
No routes matched location "/login"
react-router-dom v6
如果您尝试共享多个布局,则react-router-dom@6可以很好地处理这个问题。
react-router-dom@6
布局路线
使用GuestLayout容器的重构示例:
GuestLayout
<Routes> <Route path="/" element={<GuestLayout />}> // <-- layout wraps children routes <Route path="login" element={<Login />} /> // <-- "/login" // Optional index route if no nested routes match <Route index // <-- "/" element={<div>Default Page Content</div>} /> </Route> </Routes>
其工作原理是让父布局容器组件渲染Outlet其嵌套路由。
Outlet
const GuestLayout = () => { return ( <div /* your crazy layout styling */ > <h1>This is the Guest Layout Page</h1> <Outlet /> // <-- matched nested route rendered here </div> ); };