Similar to other answer, but IMO a little simpler.
While you could just define a flat list of routes, some guarded and some not, you could create "walled guardens" (see what I did there).
Modify your GuardedRoute
to conditionally render a Route
or Redirect
, passing all the other props through.
const GuardedRoute = ({ auth, ...rest }) => {
return auth ? <Route {...rest} /> : <Redirect to="/" />;
};
Then simply make a "guarded" section in your router. Remember that order of routes within a Switch
component matter, so order more specific paths before *less specific paths.
<Switch>
<Route exact path="/" component={Home} />
<GuardedRoute path="/protected" auth={isAutheticated}>
<Switch>
<Route path="/protected/gg" component={GG} />
<Route path="/protected" component={Protected} />
</Switch>
</GuardedRoute>
<Route path="/unprotected" component={Unprotected} />
</Switch>
I typically use codesandbox, but let me know if this forked stackblitz fails to load.
https://react-mjyp8g.stackblitz.io
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…