我正在使用 react-router-dom 版本 6.4.0 启动 React 项目,但无法为所有路由创建通用标头。
App.js - 这是我添加 RouterProvider
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;
routes.js - 在此文件中我将创建所有路线
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 />,
},
]);
Home.js - 此文件是主页,其中包含指向其他页面的链接以及标题
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;
About.js - 这是一个普通的组件,表示关于
import React from "react";
const About = () => {
return <div>About</div>;
};
export default About;
我希望 Home 和 About 组件加载时标题位于顶部。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
即使在
react-router-dom@6.4.0中,使用通用 UI 渲染布局路由仍然可以正常工作。创建一个渲染公共标头组件的布局路由组件和一个用于嵌套路由的
Outlet。示例:
const Layout = () => ( <> <CommonHeader /> <Outlet /> </> );在配置中的布局路由上导入并渲染
Layout。const routers = createBrowserRouter([ { element: <Layout />, children: [ { path: "/", element: <Home />, loader: authLoader }, { path: "/about", element: <About /> } ] } ]);...
function App() { return <RouterProvider router={routers} />; }