
React 路由守卫机制用于根据特定条件(例如用户登录状态、角色权限或数据可用性)控制对特定路由的访问。这对于保护敏感页面(如管理面板、用户资料等)至关重要。 路由守卫通过重定向未授权用户或显示错误信息来防止非法访问。
在 React 中,我们可以结合 react-router 和自定义逻辑实现路由守卫。
以下示例演示如何使用 react-router 实现基于身份验证和角色的路由守卫。
此示例保护 /dashboard 路由,只有登录用户才能访问。
创建一个 PrivateRoute 组件,检查用户登录状态:
<code class="javascript">import React from 'react';
import { Route, Navigate } from 'react-router-dom';
const PrivateRoute = ({ element, isAuthenticated, ...rest }) => {
return isAuthenticated ? element : <Navigate to="/login" />;
};
export default PrivateRoute;</code>PrivateRoute 接收 element (受保护组件), isAuthenticated (登录状态) 和其他路由属性。isAuthenticated 为 true,则渲染 element;否则重定向到 /login。在主应用中使用 PrivateRoute 保护 /dashboard 路由:
<code class="javascript">import React, { useState } from 'react';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import PrivateRoute from './PrivateRoute';
const Home = () => <h2>主页</h2>;
const Login = () => <h2>登录页</h2>;
const Dashboard = () => <h2>仪表盘 (私有)</h2>;
const App = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
return (
<BrowserRouter>
<nav>
<ul>
<li><Link to="/">主页</Link></li>
<li><Link to="/login">登录</Link></li>
<li><Link to="/dashboard">仪表盘</Link></li>
</ul>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route
path="/dashboard"
element={
<PrivateRoute isAuthenticated={isAuthenticated} element={<Dashboard />} />
}
/>
</Routes>
<div>
<button onClick={() => setIsAuthenticated(!isAuthenticated)}>
{isAuthenticated ? '退出登录' : '登录'}
</button>
</div>
</BrowserRouter>
);
};
export default App;</code>此示例保护 /admin 路由,只有具有 admin 角色的用户才能访问。
修改 PrivateRoute 组件以处理角色:
<code class="javascript">import React from 'react';
import { Route, Navigate } from 'react-router-dom';
const RoleBasedRoute = ({ element, isAuthenticated, userRole, requiredRole, ...rest }) => {
return isAuthenticated && userRole === requiredRole ? element : <Navigate to="/login" />;
};
export default RoleBasedRoute;</code>在主应用中使用 RoleBasedRoute 保护 /admin 路由:
<code class="javascript">import React, { useState } from 'react';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import RoleBasedRoute from './RoleBasedRoute';
// ... (Home, Login, Dashboard components remain the same)
const Admin = () => <h2>管理员页面 (私有)</h2>;
const App = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [userRole, setUserRole] = useState('user'); // 用户角色
return (
<BrowserRouter>
{/* ... (Navigation remains the same) */}
<Routes>
{/* ... (other routes remain the same) */}
<Route
path="/admin"
element={
<RoleBasedRoute
isAuthenticated={isAuthenticated}
userRole={userRole}
requiredRole="admin"
element={<Admin />}
/>
}
/>
</Routes>
<div>
<button onClick={() => setIsAuthenticated(!isAuthenticated)}>
{isAuthenticated ? '退出登录' : '登录'}
</button>
<button onClick={() => setUserRole(userRole === 'user' ? 'admin' : 'user')}>
切换角色 ({userRole})
</button>
</div>
</BrowserRouter>
);
};
export default App;</code>路由守卫是构建安全可靠 React 应用的关键。通过结合 react-router 和自定义逻辑,我们可以有效地控制对应用不同部分的访问权限,提升应用安全性。 记住,在实际应用中,isAuthenticated 和 userRole 通常会从后端 API 获取。
以上就是在 React 中实现 Route Guards:通过身份验证和角色保护您的路由的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号