0

我希望仅在“/checkout”和“/”期间可见,而不是在整个路径中可见。在 react reuter dom v6 中很难做到。

import React from "react";
import "./App.css";
import Header from "./Header";
import Home from "./Home";
import Checkout from "./Checkout";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Login from "./Login";

function App() {
  return (
    // BEM
    <BrowserRouter>
      <div className="app">
        <Header />
        <Routes>
          <Route path="/" element={<Home />}></Route>
          <Route path="/checkout" element={<Checkout />}></Route>
          <Route path="/login" element={<Login />}></Route>
        </Routes>
      </div>
    </BrowserRouter>
  );
}

export default App;

4

2 回答 2

0

您可以useLocation()在组件中使用钩子Header并检查pathname渲染所需的条件。

页眉.js

  import { useLocation } from "react-router-dom";
  ....
  const { pathname } = useLocation();

JSX

return (
  <div>
     {!pathname.includes("login") && <div>Not Login page</div>}
  </div>
)
于 2021-12-03T10:47:05.607 回答
0

react-routerv6 上,您可以为特定路线制作布局。您可以添加<Outlet/>以检测所有路由子项,如下面的代码。文档反应路由器

function App() {
  return (
    // BEM
    <BrowserRouter>
      <div className="app">
        <Routes>
          <Route path="/" element={<Layout/>}>
               <Route path="/" element={<Home />}></Route>
               <Route path="/checkout" element={<Checkout />}></Route>
          </Route>
          <Route path="/login" element={<Login />}></Route>
        </Routes>
      </div>
    </BrowserRouter>
  );
}

Layout.jsx 的代码

import {Outlet} from "react-router"

const Layout = () => {

    return (
        <>
            <Header/>
            <Outlet/>
        </>
    )
}

export default Layout;
于 2021-12-03T10:56:52.557 回答