React 6.4.0 所有路由器的通用标头
<p>我正在使用 <code>react-router-dom</code> 版本 6.4.0 启动 React 项目,但无法为所有路由创建通用标头。</p>
<p>App.js - 这是我添加 <code>RouterProvider</code></p> 的文件
<pre class="brush:php;toolbar:false;">import logo from './logo.svg';
import './App.css';
import { Link, Outlet, RouterProvider } from "react-router-dom";
import { routers } from "./routes/routes";
function App() {
return (
<RouterProvider router={routers}>
<div>Header</div>
<Outlet />
</RouterProvider>
);
}
export default App;</pre>
<p>routes.js - 在此文件中我将创建所有路线</p>
<pre class="brush:php;toolbar:false;">import { createBrowserRouter, redirect } from "react-router-dom";
import About from "../pages/About/About";
import Home from "../pages/Home/Home";
import { getUser, isAuthenticated } from "../sso/authUtil";
const authLoader = () => {
if (!isAuthenticated()) {
return redirect("https://google.com");
} else {
return getUser();
}
};
export const routers = createBrowserRouter([
{
path: "/",
element: <Home />,
loader: authLoader,
},
{
path: "/about",
element: <About />,
},
]);</pre>
<p>Home.js - 此文件是主页,其中包含指向其他页面的链接以及标题</p>
<pre class="brush:php;toolbar:false;">import React from "react";
import { Link, Outlet, useLoaderData } from "react-router-dom";
const Home = () => {
const loaderData = useLoaderData();
return (
<>
<div>Header</div>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<div>Home: {loaderData}</div>{" "}
<Outlet />
</>
);
}
export default Home;</pre>
<p>About.js - 这是一个普通的组件,表示关于</p>
<pre class="brush:php;toolbar:false;">import React from "react";
const About = () => {
return <div>About</div>;
};
export default About;</pre>
<p>我希望 <code>Home</code> 和 <code>About</code> 组件加载时标题位于顶部。</p>