reactjs - 防止导航组件在单个路由上呈现,但在所有其他路由上呈现
问题描述
所以我有一个 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
组件。
解决方案
您可以使用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 没有为您抛出错误。
推荐阅读
- javascript - 单击按钮时,HTML 表中的所有数据都重置为 0
- python - 我们如何使用自然语言处理技术推导出句子中与动词相关的实体?
- python - 无法通过 python paramiko 获取远程服务器上的 cpu 利用率
- django - Django Rest Frame 无法获取自嵌套对象的父 ID
- go - 我们可以在goroutine中实现goroutine吗?
- apache-flink - -m yarn-cluster 的真正含义是什么?
- pyvmomi - 如何使用 pyvmomi 检索 ESXi 主机上所有存储适配器的列表?
- python - 使用 2D 列表和 while 循环创建乘法表
- python - 用户输入以降序排列输出
- android - 将数据保存在 Fragment 中