如何在 React 中创建私有路由(路由守卫) - 例如:仅供已认证用户访问
您好!
在构建 React 应用并配置路由时,经常会遇到这种情况:您发现并非所有路由都始终公开。您可能希望某些路由仅对已认证/已授权的用户开放,或者根据业务逻辑在特定条件下启用。
我有个好消息要告诉你,你不需要任何花哨的第三方库就能实现这一点,甚至不需要精通单页应用程序的路由技术。
我将演示一个简单的解决方案,你可以轻松地将其配置到你的应用程序逻辑中。
先决条件:
- 一个路由配置完毕、可直接使用的 React 应用程序。
- 一杯好咖啡(仅限咖啡爱好者)。
问题
我的路由设置都已完成,运行正常。
<Route path="/page/home" component={Home} exact />
<Route path="/page/news" component={News} exact />
<Route path="/page/login" component={Login} exact />
<Route path="/page/profile" component={Profile} exact />
<Redirect from="/" to="/page/home" exact />
这些路由唯一的问题是任何人都可以访问该 URL /page/profile,而我只希望该路由在用户通过身份验证后可用,否则我希望他/page/login先被重定向到登录页面。
解决方案
我将创建一个简单的jsx组件tsx(适用于 React JS 或 TypeScript),它封装了库Route中的组件react-router-dom。该组件会首先检查我指定的条件,如果条件为真,则会按预期渲染该组件;否则,它会将我重定向到登录页面。
现在我们来看一下我的组件:
import React from "react";
import { Route, Redirect } from "react-router-dom";
const PrivateRoute: React.FC<{
component: React.FC;
path: string;
exact: boolean;
}> = (props) => {
const condition = performValidationHere();
return condition ? (<Route path={props.path} exact={props.exact} component={props.component} />) :
(<Redirect to="/page/login" />);
};
export default PrivateRoute;
代码讲解
该函数式组件需要三个 props:
- 在满足有效条件时要渲染的组件
Profile Page for example - 通往该组件的路径
/page/profile for example - 任何其他参数,例如
exact属性
最终结果
<Route path="/page/home" component={Home} exact />
<Route path="/page/news" component={News} exact />
<Route path="/page/login" component={Login} exact />
<PrivateRoute path="/page/profile" component={Profile} exact />
<Redirect from="/" to="/page/home" exact />
搞定了!你已经成功了,你的路由现在受到保护了。
文章来源:https://dev.to/ibrahimawadhamid/how-to-create-a-private-route-in-react-route-guard-example-for-authenticated-users-only-kin