【发布时间】:2021-12-17 16:26:43
【问题描述】:
代码:https://codesandbox.io/s/aboutlayout-o3gmd?file=/src/App.js
在Header是Routes,当你去/cabinet渲染组件<Cabinet/>时,我需要让你在路由上时/cabinet组件<Footer />不应该被渲染
尝试使用钩子const match = useRouteMatch()获取当前路径,但是必须在组件<Cabinet/>内部调用,但是我需要在组件<App/>中的路径,做一个条件,{match !== /cabinet && <Footer />}我该怎么做获取当前路径是否在<App/> 组件中?
我也想使用const match = useRef(window.location.pathname);,但它没有更新
<App/> component:
import { Redirect, Route, Switch } from "react-router-dom";
import { BrowserRouter, useRouteMatch } from "react-router-dom";
import "./styles.css";
import { Home } from "./pages/Home";
import { Catalog } from "./pages/Catalog";
import { Cabinet } from "./pages/Cabinet";
import { Header } from "./components/Header";
import { Footer } from "./components/Footer";
import { Page404 } from "./pages/Page404";
import { useRef, useState } from "react";
const App = () => {
const match = useRef(window.location.pathname);
// const [path, setPath] = useState(window.location.pathname)
console.log(match);
return (
<>
<BrowserRouter>
<Header />
<Switch>
<Route path={"/"} exact>
<Home />
</Route>
<Route path={"/catalog"} exact>
<Catalog />
</Route>
<Route path={"/cabinet"} exact>
<Cabinet />
</Route>
<Route path={"*"}>
<Page404 />
</Route>
{/* <Redirect to={'/'} /> */}
</Switch>
<Footer />
{/*
{true && <Footer />} // will be rendered
{false && <Footer />} // will not be rendered
{(match !== /cabinet) && <Footer />}
*/}
</BrowserRouter>
</>
);
};
export { App };
【问题讨论】:
-
试试这样 {(match !== '/cabinet') && }
-
是的,但是要更改
match,我需要重新加载页面,当您更改`路线`时它不会改变在codesandbox上试试这个codesandbox.io/s/aboutlayout-o3gmd?file=/src/App.js -
@Bob 我猜你可以在这种情况下使用 Layout 组件。我在 Next.js 项目中遇到了类似的问题,并像 this 一样解决了它。
标签: javascript reactjs react-hooks react-router react-router-dom