
本教程详细讲解了在 react router v6 中如何实现认证保护的私有路由和重定向。文章阐明了 `usenavigate` 钩子和 `navigate` 组件的正确用法,并提供了一个 `privateroute` 组件的实现范例,以解决常见的 `usenavigate() may be used only in the context of a
在现代单页应用(SPA)中,基于用户认证状态控制页面访问权限是一个常见需求。例如,只有登录用户才能访问某些特定页面,未登录用户则应被重定向到登录页。React Router v6 引入了新的 API 和概念,使得实现这类功能更加直观和强大。本文将深入探讨如何在 React Router v6 中构建私有路由(Private Routes)并实现条件重定向,同时解决在使用 useNavigate() 钩子时可能遇到的上下文错误。
在 React Router v6 中,旧版(如 v5)中的 Redirect 组件已被移除。现在,实现重定向主要有两种方式:
这两种方式都必须在 <Router>(例如 <BrowserRouter>)的上下文中使用。如果尝试在 <Router> 外部调用 useNavigate() 钩子,或者在 <Router> 外部使用 Navigate 组件,将会遇到 useNavigate() may be used only in the context of a <Router> component 的错误。这意味着所有的路由相关操作都必须被包裹在 <BrowserRouter> 或其他 <Router> 实现中。
为了管理用户的登录状态,我们通常会使用 React 的 Context API。这使得登录状态可以在整个应用中轻松共享,而无需通过 props 层层传递。
首先,定义一个认证上下文:
// src/context/AuthContext.js
import React, { createContext, useState, useEffect, useCallback } from 'react';
export const AuthContext = createContext({
isLoggedIn: false,
token: null,
login: () => {},
logout: () => {}
});
let logoutTimer;
export const AuthProvider = (props) => {
const [token, setToken] = useState(null);
const [isLoggedIn, setIsLoggedIn] = useState(false);
// 可以添加更多状态,例如用户信息、token过期时间等
const login = useCallback((uid, token, expirationDate) => {
setToken(token);
setIsLoggedIn(true);
// 存储 token 和过期时间到 localStorage
const tokenExpirationDate = expirationDate || new Date(new Date().getTime() + 1000 * 60 * 60); // 1小时
localStorage.setItem(
'userData',
JSON.stringify({
userId: uid,
token: token,
expiration: tokenExpirationDate.toISOString()
})
);
}, []);
const logout = useCallback(() => {
setToken(null);
setIsLoggedIn(false);
clearTimeout(logoutTimer);
localStorage.removeItem('userData');
}, []);
useEffect(() => {
if (token) {
const storedData = JSON.parse(localStorage.getItem('userData'));
if (storedData && storedData.token && new Date(storedData.expiration) > new Date()) {
const remainingTime = new Date(storedData.expiration).getTime() - new Date().getTime();
logoutTimer = setTimeout(logout, remainingTime);
}
}
}, [token, logout]);
useEffect(() => {
const storedData = JSON.parse(localStorage.getItem('userData'));
if (storedData && storedData.token && new Date(storedData.expiration) > new Date()) {
login(storedData.userId, storedData.token, new Date(storedData.expiration));
}
}, [login]);
return (
<AuthContext.Provider
value={{
isLoggedIn: !!token, // 根据 token 判断是否登录
token: token,
login: login,
logout: logout
}}
>
{props.children}
</AuthContext.Provider>
);
};PrivateRoute 组件的核心逻辑是检查用户的认证状态。如果用户已登录,则渲染其子组件(即受保护的页面);如果未登录,则使用 Navigate 组件将用户重定向到登录页面。
// src/components/PrivateRoute.js
import React, { useContext } from 'react';
import { Navigate } from 'react-router-dom';
import { AuthContext } from '../context/AuthContext'; // 引入认证上下文
const PrivateRoute = ({ children }) => {
const auth = useContext(AuthContext);
if (!auth.isLoggedIn) {
// 如果用户未登录,则重定向到 /login 页面
// replace 属性确保重定向后,用户无法通过浏览器回退按钮返回到受保护页面
return <Navigate to="/login" replace />;
}
// 如果用户已登录,则渲染子组件(即受保护的页面)
return children;
};
export default PrivateRoute;注意事项:
现在,我们可以在主应用组件中配置路由,并使用 PrivateRoute 来保护需要认证的页面。
// src/App.js
import React, { useState, useCallback } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { AuthProvider, AuthContext } from './context/AuthContext';
import PrivateRoute from './components/PrivateRoute';
// 假设这些是你的页面组件
import HomePage from './pages/HomePage';
import LoginPage from './pages/LoginPage';
import DashboardPage from './pages/DashboardPage';
import ProfilePage from './pages/ProfilePage';
import NotFoundPage from './pages/NotFoundPage'; // 404 页面
const App = () => {
return (
// AuthProvider 应该包裹在 Router 外部,以便所有路由和组件都能访问认证上下文
<AuthProvider>
<Router>
<div className="App">
{/* 这里可以放置全局导航栏或其他布局组件 */}
<Routes>
{/* 公共路由,无需认证即可访问 */}
<Route path="/" element={<HomePage />} />
<Route path="/login" element={<LoginPage />} />
{/* 私有路由,需要认证才能访问 */}
<Route
path="/dashboard"
element={
<PrivateRoute>
<DashboardPage />
</PrivateRoute>
}
/>
<Route
path="/profile"
element={
<PrivateRoute>
<ProfilePage />
</PrivateRoute>
}
/>
{/* 匹配所有未定义路由的 404 页面 */}
<Route path="*" element={<NotFoundPage />} />
</Routes>
</div>
</Router>
</AuthProvider>
);
};
export default App;关键点:
通过上述方法,我们成功地在 React Router v6 中实现了强大的认证保护私有路由和重定向机制。这种模式不仅解决了 useNavigate() may be used only in the context of a <Router> component 的常见错误,还提供了一个清晰、可维护的方案来管理用户权限。
核心要点回顾:
遵循这些实践,您将能够构建出更加健壮、安全且用户友好的 React 应用。
以上就是React Router v6 教程:构建认证保护的私有路由与重定向策略的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号