保护前端页面基本是说,一些页面,例如修改密码,必须登录才可以访问,如果在没有登录的情况下可以访问这类页面,即使操作失败,也会显得很奇怪。然后,这类页面在退出登录后应该重定向转到其他页面,否则一样奇怪。
因此,保护这类页面是有必要的。
条件添加路由是解决这类问题的标准方式,在 App.js中 设置路由,受保护的路由仅仅在用户登录后才存在。
sample code:
function App() {
const authCtx = useContext(AuthContext);
return (
<Layout>
<Switch>
<Route path="/" exact>
<HomePage />
</Route>
{!authCtx.isLoggedIn && (
<Route path="/auth">
<AuthPage />
</Route>
)}
{authCtx.isLoggedIn && (
<Route path="/profile">
<UserProfile />
</Route>
)}
<Route path="*">
<Redirect to="/" />
</Route>
</Switch>
</Layout>
);
}
export default App;
上述代码段:
{authCtx.isLoggedIn && (
<Route path="/profile">
<UserProfile />
</Route>
)}
也可以修改成下面这样,如果用户试图访问需要登录才可以访问的页面,跳转到登录,这种写法也很好。
<Route path="/profile">
{authCtx.isLoggedIn && <UserProfile />}
{!authCtx.isLoggedIn && <Redirect to="/auth" />}
</Route>