隐藏导航栏功能不起作用 useLocation

时间:2021-05-13 07:14:52

标签: reactjs react-router-dom

谁能告诉我为什么这个功能没有给我想要的结果。我错过了一些明显的东西吗?当我控制台日志

import React from 'react'
import Navbar from './Components/Navbar'
import {BrowserRouter as Router, Route} from 'react-router-dom';
import Home from './Components/Home'
import Welcome from './Components/Welcome'
import About from './Components/About'
import Contact from './Components/Contact'


    function App() {
  return (
    <>
    <useLocation> 
      {({ useLocation }) => { 
        if (useLocation.pathname !== "/") { return <Navbar/>; } }
      } 
    </useLocation>
    <Router>
      <Route exact path="/" component={Welcome}/>
      <Route path="/Home" component={Home}/>
      <Route path="/About" component={About}/>
      <Route path='/Whitepaper' component={WhitePaper}/>
    </Router>
    </>
  );
}

export default App;

1 个答案:

答案 0 :(得分:1)

我认为将 Navbar 组件渲染为路由并检查 route props 中传递的 location 会更好。

function App() {
  return (
    <Router>
      <Route
        render={({ location }) => location.pathname !== "/" ? <Navbar/> : null}
      />
      <Route exact path="/" component={Welcome}/>
      <Route path="/Home" component={Home}/>
      <Route path="/About" component={About}/>
      <Route path='/Whitepaper' component={WhitePaper}/>
    </Router>
  );
}