React Router - How to redirect user if logged in?

人盡茶涼 提交于 2021-01-28 07:40:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!