如何使用React Router在登录页面隐藏导航栏?
Hey there! As a React newbie, this is such a common scenario—let's work through this together so your NavBar only shows up where you want it.
The issue right now is that your <NavBar /> is rendered unconditionally in your App component, so it appears on every route. To hide it specifically on the /signin page, we need to conditionally render the NavBar based on the current route path.
Solution for Class Components (Your Current Setup)
Since you're using a class-based App component, we'll use the withRouter higher-order component from react-router-dom to access the current route location. Here's how to adjust your code:
- First, import
withRouteralongside your other router imports. - Use
this.props.locationto get the current pathname. - Add a condition to only render the NavBar when we're NOT on the
/signinpath.
Modified App.js code:
import React from "react"; import { Route, Switch, withRouter } from 'react-router-dom'; // Ensure you've imported your components like NavBar, HomePage, etc. class App extends React.Component { render() { const { location } = this.props; return ( <div> {/* Conditionally render NavBar */} {location.pathname !== '/signin' && <NavBar />} <Switch> <Route exact={true} path='/' component={HomePage} /> <Route path='/men' component={MensPage} /> <Route path='/woman' component={WomansPage} /> <Route path='/signin' component={SignInAndSignUpPage} /> </Switch> </div> ) } }; // Wrap App with withRouter to inject route-related props export default withRouter(App);
Quick Explanation
withRouterwraps yourAppcomponent and passes route-specific props (likelocation) to it. This lets you check exactly what page the user is viewing.- The condition
location.pathname !== '/signin'translates to: "Only display the NavBar if the current page isn't the sign-in page."
Bonus: Solution for Functional Components (If You Switch Later)
Once you're comfortable with functional components, you can use the useLocation hook for a more streamlined approach:
import React from "react"; import { Route, Switch, useLocation } from 'react-router-dom'; function App() { const location = useLocation(); return ( <div> {location.pathname !== '/signin' && <NavBar />} <Switch> <Route exact path='/' component={HomePage} /> <Route path='/men' component={MensPage} /> <Route path='/woman' component={WomansPage} /> <Route path='/signin' component={SignInAndSignUpPage} /> </Switch> </div> ) }; export default App;
That's all there is to it! This should make your NavBar disappear on the sign-in page while staying visible on all other routes. Let me know if you hit any snags getting this set up.
内容的提问来源于stack exchange,提问作者mr_vmoore

