首页 > 解决方案 > 防止导航组件在单个路由上呈现,但在所有其他路由上呈现

问题描述

所以我有一个 Route /reminder,我不想要我的Navigation组件,但我希望Navigation组件在所有其他 Route 上呈现,我不知道该怎么做?

这是我App.js用于react-router-dom路由的地方。

import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Navigation from "./components/navigation/Navigation";
import Reminder from "./components/reminder/Reminder ";

const App = () => {

  return (
    <>
      <Switch>
        <Route path="/reminder" component={Reminder} exact />
      </Switch>
      <Navigation />
      <MainContent>
        <Router>
          <Route path={"/"} component={Dashboard} exact />
        </Router>
      </MainContent>
    </>
  );
}

我环顾四周寻找类似的问题,但主要是针对经过身份验证的页面,而不是针对经过身份验证的页面。

我不想沿着必须将Navigation组件添加到我当前的 21 条路线中的路线走下去,似乎应该有更好的方法?

使用上面我当前的代码,它呈现Reminder组件但仍呈现Navigation组件。

标签: reactjsreact-routerreact-router-dom

解决方案


您可以使用react-router 中的自定义挂钩访问匹配数据。你需要做的就是

import { useRouteMatch } from "react-router-dom";

function App() {
  let match = useRouteMatch("/reminder");

  // Do whatever you want with the match...
  return (
<>
  <Switch>
    <Route path="/reminder" component={Reminder} exact />
  </Switch>
  {!match && <Navigation />} <---Conditional rendering
  <MainContent>
    <Router>
      <Route path={"/"} component={Dashboard} exact />
    </Router>
  </MainContent>
</>
  );
    }

此外,虽然我没有在您的示例中更改这一点,但在路由器组件之外设置路由通常不是一个好主意。实际上,我有点惊讶 react-router-dom 没有为您抛出错误。


推荐阅读