react如何拦截是否登录
拦截登录状态的常见方法
在React中拦截登录状态通常通过路由守卫、全局状态管理或高阶组件实现。以下是几种典型方案:
路由守卫(React Router v6)
使用Navigate组件和useNavigate钩子实现路由拦截:
import { Navigate, useNavigate } from 'react-router-dom';
const PrivateRoute = ({ children }) => {
const isAuthenticated = localStorage.getItem('token');
return isAuthenticated ? children : <Navigate to="/login" />;
};
// 使用示例
<Route path="/dashboard" element={<PrivateRoute><Dashboard /></PrivateRoute>} />
高阶组件(HOC)方案
创建高阶组件包裹需要保护的组件:

function withAuth(Component) {
return function AuthenticatedComponent(props) {
const isLoggedIn = /* 登录状态判断逻辑 */;
return isLoggedIn
? <Component {...props} />
: <Redirect to="/login" />;
};
}
// 使用示例
const ProtectedPage = withAuth(Dashboard);
全局状态管理(Redux/Context)
结合Redux实现全局状态监听:
import { useSelector } from 'react-redux';
function AuthWrapper({ children }) {
const { isAuthenticated } = useSelector(state => state.auth);
return isAuthenticated ? children : null;
}
// 在Redux中配置登录状态变更监听
store.subscribe(() => {
const state = store.getState();
if (!state.auth.isAuthenticated) {
// 跳转登录页
}
});
拦截HTTP请求
使用axios拦截器处理未认证请求:

axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
window.location.href = '/login';
}
return Promise.reject(error);
}
);
自定义Hook方案
创建useAuth钩子统一管理认证逻辑:
function useAuth() {
const [isAuth, setIsAuth] = useState(false);
useEffect(() => {
const token = localStorage.getItem('token');
setIsAuth(!!token);
}, []);
return { isAuth };
}
// 使用示例
function ProtectedComponent() {
const { isAuth } = useAuth();
return isAuth ? <MainContent /> : <LoginPage />;
}
服务端渲染(SSR)场景
在getServerSideProps中验证:
export async function getServerSideProps(context) {
const { req } = context;
if (!req.cookies.token) {
return {
redirect: {
destination: '/login',
permanent: false,
},
};
}
return { props: {} };
}
每种方案适用于不同场景,路由守卫适合SPA应用,高阶组件适合组件级控制,全局状态管理适合复杂应用,HTTP拦截适合API请求统一处理。实际开发中常组合使用多种方式。






