react实现页面登录的几种方式检查
方法整理
| 方案 | 适用版本 | 实现关键点 | 优缺点 |
|---|---|---|---|
| React Router v6 | ✅ React Router v6 |
|
✅ 优点: 代码简洁,受保护路由统一管理。 ❌ 缺点: 仅适用于 React Router v6。 |
| React Router v5 | ✅ React Router v5 及更早版本 |
自定义一个路由渲染组件 |
✅ 优点: 适用于 React Router v5,逻辑清晰。 ❌ 缺点: React Router v6 已经弃用 ``,需要修改代码。 |
| 高阶组件(HOC) | ✅ 适用于所有版本(不依赖 `react-router`) |
每个需要验证的页面组件都包装一层 |
✅ 优点: 代码复用性高,可用于 `Route` 也可用于普通组件。 ❌ 缺点: 组件必须手动 `export default withAuth(Component)`。复用性不够好 |
代码实现
1.React Router v6
import { BrowserRouter as Router, Routes, Route, Navigate, Outlet } from "react-router-dom";
// 认证检查函数
const isAuthenticated = () => !!localStorage.getItem("access_token");
// 受保护路由组件
const PrivateRoute = () => {
return isAuthenticated() ? <Outlet /> : <Navigate to="/login" replace />;
};
const Dashboard = () => <h1>Dashboard</h1>;
const Login = () => <h1>Login Page</h1>;
const Home = () => <h1>Home</h1>;
function App() {
return (
<Router>
<Routes>
{/* 公共页面 */}
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
{/* 受保护的路由 */}
<Route element={<PrivateRoute />}>
<Route path="/dashboard" element={<Dashboard />} />
</Route>
</Routes>
</Router>
);
}
export default App;
2. React Router v5
import { BrowserRouter as Router, Route, Redirect, Switch } from "react-router-dom";
// 认证检查
const isAuthenticated = () => !!localStorage.getItem("access_token");
// 受保护路由
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={(props) =>
isAuthenticated() ? <Component {...props} /> : <Redirect to="/login" />
}
/>
);
const Dashboard = () => <h1>Dashboard</h1>;
const Login = () => <h1>Login Page</h1>;
const Home = () => <h1>Home</h1>;
function App() {
return (
<Router>
<Switch>
{/* 公共页面 */}
<Route path="/" exact component={Home} />
<Route path="/login" component={Login} />
{/* 受保护的路由 */}
<PrivateRoute path="/dashboard" component={Dashboard} />
</Switch>
</Router>
);
}
export default App;
3. 高阶组件
1️⃣ 创建 withAuth 高阶组件
import React from "react"; import { Redirect } from "react-router-dom"; // 判断是否登录 const isAuthenticated = () => !!localStorage.getItem("access_token"); // 高阶组件:封装权限校验逻辑 const withAuth = (WrappedComponent) => { return (props) => { if (!isAuthenticated()) { return <Redirect to="/login" />; } return <WrappedComponent {...props} />; }; }; export default withAuth;
2️⃣ 受保护页面使用 withAuth 包裹
import React from "react"; import withAuth from "./withAuth"; const Dashboard = () => { return <h1>Dashboard - 需要登录才能访问</h1>; }; // 使用 HOC 进行权限校验 export default withAuth(Dashboard);

浙公网安备 33010602011771号