У меня есть глобальный компонент заголовка внутри моего маршрутизатора. Но я хочу скрыть на странице входа.
Я пытался использовать решение window.location, подобное этому. Это работает, но не работает после того, как страница входа переходит на домашнюю страницу. (он не показывает заголовок, пока я не обновлю страницу)
App.js
import React, { useState, useEffect } from "react";
import "./sass/app.scss";
import { db, auth } from "./configs/firebase-config";
import { MainContext } from "./hooks/Context";
import { eventbriteRoutes } from "./configs/routes";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Header from "./components/Home/Header";
function App() {
const [isAuth, setIsAuth] = useState(localStorage.getItem("isAuth"));
const data = {
isAuth,
setIsAuth,
};
return (
<>
<MainContext.Provider value = {data}>
<Router>
{window.location.pathname !== "/login" ? <Header /> : null}{" "}
<Routes>
{eventbriteRoutes.map((RouteItem, index) => (
<Route
exact
key = {index}
path = {RouteItem.path}
element = {RouteItem.element}
/>
))}
</Routes>
</Router>
</MainContext.Provider>
</>
);
}
export default App;
Создайте маршрут макета, который отображает (условно) компонент Header
и компонент Outlet
для вложенных компонентов маршрута.
Пример:
import { Outlet, useLocation } from 'react-router-dom';
const Layout = ({ hideHeaderPaths = [] }) => {
const { pathname } = useLocation();
return (
<>
{!hideHeaderPaths.includes(pathname) && <Header />}
<Outlet />
</>
);
}
...
function App() {
const [isAuth, setIsAuth] = useState(localStorage.getItem("isAuth"));
const data = {
isAuth,
setIsAuth,
};
return (
<>
<MainContext.Provider value = {data}>
<Router>
<Routes>
<Route element = {<Layout hideHeaderPaths = {["/login"]} />}>
{eventbriteRoutes.map((RouteItem) => (
<Route
key = {RouteItem.path}
path = {RouteItem.path}
element = {RouteItem.element}
/>
))}
</Route>
</Routes>
</Router>
</MainContext.Provider>
</>
);
}
Или, если проще просто отделить маршрут "/login"
, вы можете просто создать маршрут макета, который безоговорочно отображает компонент Header
и отдельно обрабатывает маршрут входа.
Пример:
import { Outlet } from 'react-router-dom';
const HeaderLayout = () => (
<>
<Header />
<Outlet />
</>
);
...
function App() {
const [isAuth, setIsAuth] = useState(localStorage.getItem("isAuth"));
const data = {
isAuth,
setIsAuth,
};
return (
<>
<MainContext.Provider value = {data}>
<Router>
<Routes>
<Route path = "/login" element = {<Login />} />
<Route element = {<HeaderLayout} />}>
{eventbriteRoutes.map((RouteItem) => (
<Route
key = {RouteItem.path}
path = {RouteItem.path}
element = {RouteItem.element}
/>
))}
</Route>
</Routes>
</Router>
</MainContext.Provider>
</>
);
}