简体   繁体   English

在所有路径中显示组件,除了 react-router-dom v6 中的一些

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

I'm attempting to create a few routes on my web app using react-router .我正在尝试使用react-router在我的 web 应用程序上创建一些路线。 However, some pages need to share components - such as the Navigation or Footer - where others do not.但是,某些页面需要共享组件——例如NavigationFooter ——而其他页面则不需要。

What I essentially need is a way to check if a path doesn't match a few preset locations, and if it doesn't then render the content.我本质上需要的是一种方法来检查路径是否与一些预设位置匹配,如果不匹配则呈现内容。

At the moment I'm doing this like so:目前我正在这样做:

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>
);

However, ever since V6 of react-router-dom has been introduced, this doesn't seem to work.但是,自从引入了react-router-dom V6以来,这似乎不起作用。 I imagine this is because the render prop has been deprecated (although I'm unsure, but there's no mention of it in the docs).我想这是因为render道具已被弃用(虽然我不确定,但文档中没有提到它)。

Are there any workarounds - or a better implementation of this which works with V6 ?是否有任何变通方法 - 或与V6一起使用的更好的实现? Cheers干杯

Create a layout component that renders the UI components you want and an Outlet for nested routes to be rendered into.创建一个布局组件来呈现您想要的 UI 组件一个用于渲染嵌套路由的Outlet

Example:例子:

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