React Router 4 - Hide Navigation when on “/” route

2019-09-14 17:33发布

问题:

I have a following code, with such imports:

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from 'react-router-dom'

import { Comics } from './Comics';
import { Books } from './Books';
import { Projects } from './Projects';
import { Navigation } from './Navigation';

function App() {
return (
  <Router>
    <div className="App">
      <Navigation loggedInUser={loggedInUser} />
      <Route path="/" exact component={Home} />

      <Switch>    
        <Route path= "/comics" component={Comics} />
        <Route path="/books" component={Books}/>
        <Route path="/projects" component={Projects} />
      </Switch>
    </div>
  </Router>
)
}

How to hide navigation when I am on "/" route? I could render Navigation on each route but I don't think this is a good idea performance wise?

回答1:

The path parameter to Route understands any regex compatible with path-to-regexp so you could choose to render the Navigation component only when there is at least one character in the path after the slash like this

<Route path="/(.+)" render={(() => 
    <Navigation loggedInUser={loggedInUser} />
)}/>


标签: react-redux