How to restrict access to routes in react-router?

后端 未结 7 1528
暗喜
暗喜 2020-12-07 08:49

Does anyone know how to restrict access to particular routes in react-router? I want to check if the user is logged in before allowing access to a particular route. I though

相关标签:
7条回答
  • 2020-12-07 09:33

    react-router encourages a declarative approach for your router, you should make your router as dumb as possible and avoid putting your routing logic in your components.

    Here is how you can do it (assuming you pass it the loggedIn prop):

    const DumbRouter = ({ loggedIn }) => (
      <Router history={history}>
        <Switch>
          {[
            !loggedIn && LoggedOutRoutes,
            loggedIn && LoggedInRouter,
            <Route component={404Route} />
          ]}
        </Switch>
      </Router>
    );
    
    const LoggedInRoutes = [
      <Route path="/" component={Profile} />
    ];
    
    const LoggedOutRoutes = [
      <Route path="/" component={Login} />
    ];
    
    0 讨论(0)
提交回复
热议问题