You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用React Router v6的Outlet和localStorage实现私有路由?

React Router v6 实现登录保护路由方案

1. 创建路由保护组件 ProtectedRoute

这个组件会检查用户登录状态,仅允许已登录用户访问子路由页面,未登录用户会被重定向到登录页。

import { Navigate, Outlet } from 'react-router-dom';
import { useSelector } from 'react-redux';

const ProtectedRoute = () => {
  // 从redux store读取登录状态,需确保你的store中auth模块包含isLoggedIn字段
  const isLoggedIn = useSelector(state => state.auth.isLoggedIn);

  return isLoggedIn ? <Outlet /> : <Navigate to="/login" replace />;
};

export default ProtectedRoute;

2. 修改路由配置

将需要保护的页面(Account/History/Deposit/Withdrawal)嵌套到ProtectedRoute下,开放页面(Home/Login)保持原有配置:

// index.js
import ProtectedRoute from './ProtectedRoute';

const router = createBrowserRouter([
  {
    path: "/",
    element: <App />,
    children: [
      { path: "/", element: <Home /> },
      { path: "login", element: <Login /> },
      // 受保护路由组
      {
        element: <ProtectedRoute />,
        children: [
          { path: "account", element: <Account /> },
          { path: "history", element: <History /> },
          { path: "deposit", element: <Deposit /> },
          { path: "withdrawal", element: <Withdrawal /> },
        ],
      },
    ],
  },
]);

3. 维护登录状态

确保你的redux store中正确管理登录状态:

  • 登录成功时,dispatch action将auth.isLoggedIn设为true
  • 注销时,dispatch action将auth.isLoggedIn设为false

关键说明

  • <Navigate replace />:替换当前路由历史记录,避免用户通过后退按钮回到未登录时访问的受保护页面
  • 嵌套路由+Outlet的逻辑和你在App组件中使用的方式一致,无需额外学习成本

内容的提问来源于stack exchange,提问作者zooboomafoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 05:51:18