簡體   English   中英

在所有路徑中顯示組件,除了 react-router-dom v6 中的一些

[英]display component across all paths except some in react-router-dom v6

我正在嘗試使用react-router在我的 web 應用程序上創建一些路線。 但是,某些頁面需要共享組件——例如NavigationFooter ——而其他頁面則不需要。

我本質上需要的是一種方法來檢查路徑是否與一些預設位置匹配,如果不匹配則呈現內容。

目前我正在這樣做:

const displayComponentIfAllowed = (location, component) => {
    const C = component;
    const globalComponentsDisallowedPaths = ["/booking"];

    // If the path matches something within the blocked list, then return null.
    let allowToRender = true;
    globalComponentsDisallowedPaths.forEach(disallowedPath => {
        if(location.pathname === disallowedPath){
            allowToRender = false;
        }
    });

    // Otherwise, return component to render.
    return allowToRender ? <C /> : null;
}

return (
    <Router>
        <Routes>
            <Route render={({ location }) => displayComponentIfAllowed(location, Navigation)} />
            <Route path="/">
                <Route index element={<Home />} />
                <Route path="booking/:customer_id" element={<Booking />} />
            </Route>
            <Route render={({ location }) => displayComponentIfAllowed(location, Footer)} />
        </Routes>
    </Router>
);

但是,自從引入了react-router-dom V6以來,這似乎不起作用。 我想這是因為render道具已被棄用(雖然我不確定,但文檔中沒有提到它)。

是否有任何變通方法 - 或與V6一起使用的更好的實現? 干杯

創建一個布局組件來呈現您想要的 UI 組件一個用於渲染嵌套路由的Outlet

例子:

import { Outlet } from 'react-router-dom';

const HeaderFooterLayout = () => (
  <>
    <Navigation />
    <Outlet />
    <Footer />
  </>
);

...

import {
  BrowserRouter as Router,
  Routes,
  Route
} from "react-router-dom";

...

<Router>
  <Routes>
    <Route element={<HeaderFooterLayout />} >
      <Route path="/">
        <Route index element={<Home />} />
        ... other routes you want to render with header/footer ...
      </Route>
    </Route>
    <Route path="booking/:customer_id" element={<Booking />} />
    ... other routes you want to not render with header/footer ...
  </Routes>
</Router>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM