如何在反应中隐藏某些页面的页脚组件

How to hide Footer component for some pages in react

我想在某些页面中隐藏页脚组件

app.js

<div className="App">
  <Header setShowMenu={setShowMenu} />
  {showMenu ? <Menu navigateTo={navigateTo} setShowMenu={setShowMenu} /> : null}
  <Main navigateTo={navigateTo} />
  <Footer navigateTo={navigateTo} />
</div>

main.jsx

<div>
    <Routes>
        <Route path="/" element={<HomePage navigateTo={navigateTo} />}  />
        <Route path="/precard" element={<PreCard />}  />
        <Route path="/order" element={<Order />}  />
        <Route path="/contact" element={<Contact />}  />
        <Route path="/thankspage" element={<ThanksPage navigateTo={navigateTo}/>}  />
        <Route path="/*" element={<HomePage />} />
    </Routes>
</div>

注:路由器在index.js

所以我想在 ./order 页面中隐藏页脚

我希望你们能为我提供解决方案:)

你可以使用useLocation()钩子来检查<Footer />组件中的路由路径,并基于pathname你可以渲染<Footer />组件。

示例:

import React from "react";
import { useLocation } from "react-router-dom";

const Footer = () => {
  const { pathname } = useLocation();
  console.log(pathname);
  // you can check a more conditions here
  if (pathname === "/thanks") return null;

  return <div className="footer">Footer</div>;
};
export { Footer };

App.js

import { Route, Switch, BrowserRouter } from "react-router-dom";
import "./styles.css";
import { Home } from "./pages/Home";
import { Catalog } from "./pages/Catalog";
import { Thanks } from "./pages/Thanks";
import { Header } from "./components/Header";
import { Footer } from "./components/Footer";
import { Page404 } from "./pages/Page404";

const App = () => {

  return (
    <>
      <BrowserRouter>
        <Header />
        <Switch>
          <Route path={"/"} exact>
            <Home />
          </Route>
          <Route path={"/catalog"} exact>
            <Catalog />
          </Route>
          <Route path={"/thanks"} exact>
            <Thanks />
          </Route>
          <Route path={"*"}>
            <Page404 />
          </Route>
          {/* <Redirect to={'/'} /> */}
        </Switch>
        <Footer />
      </BrowserRouter>
    </>
  );
};

export { App };