react-router-dom@6 的布局路由无法按预期工作
Posted
技术标签:
【中文标题】react-router-dom@6 的布局路由无法按预期工作【英文标题】:Layout Route does not work as expected with react-router-dom@6 【发布时间】:2022-01-21 22:12:19 【问题描述】:我正在使用 react-router-dom@6.2。 当试图用“DefaultLayout”元素手动包装我的元素时,一切似乎都很好:
<Route path="/privacy" element=<PageLayout><Privacy /></PageLayout> />
<Route path="/tos" element=<PageLayout><Tos /></PageLayout> />
但是,当尝试使用时:
<Route element=<PageLayout />>
<Route path="/privacy" element=<Privacy /> />
<Route path="/tos" element=<Tos /> />
</Route>
我只得到没有“子”元素的页眉和页脚。 可能是什么原因?
【问题讨论】:
【参考方案1】:尝试像这样用<Routes>
包装你的代码:
<Routes>
<Route element=<PageLayout />>
<Route path="/privacy" element=<Privacy /> />
<Route path="/tos" element=<Tos /> />
</Route>
</Routes>
index.js在这里你有来自docs的例子如何使用react-router-dom@v6
import * as React from "react";
import * as ReactDOM from "react-dom";
import BrowserRouter from "react-router-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
App.js
import * as React from "react";
import Routes, Route, Link from "react-router-dom";
import "./App.css";
function App()
return (
<div className="App">
<h1>Welcome to React Router!</h1>
<Routes>
<Route path="/" element=<Home /> />
<Route path="about" element=<About /> />
</Routes>
</div>
);
【讨论】:
感谢您的快速回复。但是,我的代码已经用好的。问题解决了。 布局页面应呈现元素以使其正常工作。 看起来是这样的:
** 默认布局 **
import React from "react";
import Header from "./partials/Header";
import Footer from "./partials/Footer";
import Outlet from "react-router-dom";
export const DefaultLayout = () =>
return (
<div className="default-layout">
<header className="header">
<Header />
</header>
<main className="main">
<Outlet />
</main>
<footer className="footer">
<Footer />
</footer>
</div>
);
;
** app.js **
import "./App.css";
import BrowserRouter as Router, Routes, Route from "react-router-dom";
import DefaultLayout from "./components/layout/DefaultLayout";
import AddTicket from "./pages/add-ticket/AddTicket";
import Dashboard from "./pages/dashboard/Dashboard";
import Entry from "./pages/entry/Entry";
import TicketList from "./pages/ticket-list/TicketList";
import Ticket from "./pages/ticket/Ticket";
function App()
return (
<Router>
<Routes>
<Route path="/" element=<Entry /> />
<Route element=<DefaultLayout />>
<Route path="/dashboard" element=<Dashboard /> />
<Route path="/tickets" element=<TicketList /> />
<Route path="/ticket" element=<Ticket /> />
<Route path="/add-ticket" element=<AddTicket /> />
</Route>
</Routes>
</Router>
);
export default App;
【讨论】:
以上是关于react-router-dom@6 的布局路由无法按预期工作的主要内容,如果未能解决你的问题,请参考以下文章
使用react-router-dom@6,如何完成路由守卫这样的功能——使用高阶组件的包裹。
使用react-router-dom@6,如何完成路由守卫这样的功能——使用高阶组件的包裹。