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

React Router DOM v5升v6:Redirect组件替换为navigate问题求助

React Router v5 升级到 v6:替换 Redirect 与重构路由逻辑

React Router v6 移除了 <Redirect> 组件,同时也废弃了 Route 的 render prop,以下是适配你原有认证路由逻辑的具体方案:

核心替代规则

  • 用 <Navigate> 组件替换 <Redirect>,如果需要和原 <Redirect> 一样替换当前历史记录,记得加上 replace={true} 属性
  • 废弃 Route 的 render/component prop,统一用 element 传递组件,推荐封装自定义「私有路由组件」来处理认证逻辑

适配你的代码示例

第一步:封装私有路由组件

根据你原来的逻辑(已认证则跳转到 Dashboard,否则渲染目标组件),提供两种封装形式:

形式一:通过 Children 传递单个组件

import { Navigate } from 'react-router-dom';

// 自定义私有路由组件
const ProtectedRoute = ({ authenticated, children }) => {
  // 已认证则跳转到 Dashboard,否则渲染目标组件
  return authenticated ? (
    <Navigate 
      to="/dashboard" 
      replace 
      state={{ from: window.location.pathname }} 
    />
  ) : (
    children
  );
};

形式二:用 Outlet 批量处理私有路由(更推荐)

如果有多个需要认证的页面,用 Outlet 可以批量嵌套路由,写法更简洁:

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

const ProtectedRoute = ({ authenticated }) => {
  // 已认证则渲染所有嵌套的私有路由,否则跳转到登录页
  if (authenticated) {
    return <Outlet />;
  }
  // 记录当前访问路径,方便登录后跳转回来
  return <Navigate to="/login" replace state={{ from: window.location.pathname }} />;
};

第二步:在路由配置中使用

单个组件的用法(对应形式一)

import { Routes, Route } from 'react-router-dom';

function App() {
  const authenticated = false; // 替换成你的真实认证状态

  return (
    <Routes>
      {/* 未认证时可访问的组件 */}
      <Route 
        path="/your-public-page" 
        element={
          <ProtectedRoute authenticated={authenticated}>
            <YourPublicComponent />
          </ProtectedRoute>
        } 
      />
      
      {/* 已认证后跳转的 Dashboard */}
      <Route path="/dashboard" element={<Dashboard />} />
    </Routes>
  );
}

批量私有路由的用法(对应形式二)

import { Routes, Route } from 'react-router-dom';

function App() {
  const authenticated = false; // 替换成你的真实认证状态

  return (
    <Routes>
      {/* 公共路由 */}
      <Route path="/login" element={<Login />} />

      {/* 所有嵌套在此的路由都需要认证 */}
      <Route element={<ProtectedRoute authenticated={authenticated} />}>
        <Route path="/dashboard" element={<Dashboard />} />
        <Route path="/profile" element={<Profile />} />
      </Route>
    </Routes>
  );
}

补充:获取跳转来源的状态

如果需要在登录页获取用户「原本想访问的路径」,可以用 useLocation 钩子:

import { useLocation, useNavigate } from 'react-router-dom';

function Login() {
  const location = useLocation();
  const navigate = useNavigate();
  // 默认跳转到 Dashboard,若有来源路径则优先使用
  const from = location.state?.from || '/dashboard';

  const handleLogin = () => {
    // 登录成功后跳转到用户原本想访问的页面
    navigate(from, { replace: true });
  };

  return (
    // 登录表单代码...
    <button onClick={handleLogin}>登录</button>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:32:48