问题
I'm using react-router-dom to manage my routes:
const Routes = () => {
return (
<BrowserRouter>
<div>
<Route path="/" component={Navbar} />
<Switch>
<Route exact path="/" component={Main} />
<Route path="/signin" component={SignIn} />
<Route path="/signup" component={SignUp} />
<PrivateRoute path="/dashboard" component={DashboardRoutes} />
<Route path="*" component={() => <h1>Page not found</h1>} />
</Switch>
</div>
<div>
<Route path="/" component={Footer} />
</div>
</BrowserRouter>
);
};
I want only to render the Navbar
if the user is not authenticated. If the user is authenticated, I don't want to render the Navbar
and I want to redirect him to dashboard.
I tried with inline conditioning:
const Routes = () => {
return (
<BrowserRouter>
<div>
{!isAuthenticated() && <Route path="/" component={Navbar} />}
<Switch>
<Route exact path="/" component={Main} />
<Route path="/signin" component={SignIn} />
<Route path="/signup" component={SignUp} />
<PrivateRoute path="/dashboard" component={DashboardRoutes} />
<Route path="*" component={() => <h1>Page not found</h1>} />
</Switch>
</div>
<div>
<Route path="/" component={Footer} />
</div>
</BrowserRouter>
);
};
However, when I'm not logged in, and then sign in, the Navbar
persists, because it was rendered when isAuthenticated
was false.
How can I achieve this?
Thanks!
PS: I already have a isAuthenticated
function.
回答1:
A better way to handle this would be in your Navbar component itself.
In your Navbar component, setup componentDidMount()
to check if the user isAuthenticated and just redirect them.
componentDidMount(){
if(isAuthenticated()){
this.props.history.push("/dashboard")
}
}
And in the render(), just use the isAuthenticated
() method you set up to determine if you should return anything.
render(){
if(!isAuthenticated()){
return(
...your navbar markup
) else {
return null
}
}
}
来源:https://stackoverflow.com/questions/56353125/react-router-how-to-redirect-user-if-logged-in