问题
Is there a way I can hide my page header for only some routes in React Router? My issue now is that my App
component renders my Main
component, which contains my BrowserRouter
, and my Header
is rendered in my App
component, so I have no way of rendering the header based on the route path.
Here's some code:
App.js
import React from 'react';
import {BrowserRouter} from 'react-router-dom';
import Main from './Main';
import Header from './Header';
import Footer from './Footer';
const App = () => (
<BrowserRouter>
<Header/>
<Main/>
<Footer/>
</BrowserRouter>
);
export default App;
Main.js
import React from 'react';
import {Route, Switch} from 'react-router-dom';
import Home from './Home';
import Login from './Login';
const Main = () => (
<main>
<Switch>
<Route exact path='/' component={Home}/>
<Route exact path='/login' component={Login}/>
</Switch>
</main>
);
export default Main;
In this application, I would like to hide the header and footer on the login page.
回答1:
I ended up using Redux. This was the best option because I have over twenty pages (only 3 shown in code below) on all of which the visibility of the header/footer vary. I created one reducer for the header and one for the footer. Here was my solution:
import ...
class App extends React.Component {
render() {
return (
<BrowserRouter>
{this.props.header ? <Header/> : ''}
<Switch>
<Route exact path='/' component={Home}/>
<Route exact path='/login' component={Login}/>
<Route exact path='/signup' component={Signup}/>
</Switch>
{this.props.footer ? <Footer/> : ''}
</BrowserRouter>
);
}
}
const mapStateToProps = state => state;
export default connect(mapStateToProps)(App);
回答2:
You can use withRouter Higher-Order component to access props.location object in your App component and check if a user is on login or signup page using props.location.pathname
import {BrowserRouter, withRouter} from 'react-router-dom'
const App = () => (
<BrowserRouter>
{
props.location.pathname!=='/login' ? <Header/>:null
}
<Main/>
<Footer/>
</BrowserRouter>
);
export default withRouter(App);
来源:https://stackoverflow.com/questions/56971917/hide-header-on-some-pages-in-react-router-dom