You need to enable JavaScript to run this app. 已认证状态下仍可跳转回登录组件,如何限制已登录用户访问登录路由
优惠活动
大模型
产品
解决方案
定价
更多

已认证状态下仍可跳转回登录组件,如何限制已登录用户访问登录路由

问题原因

你当前的路由鉴权逻辑只覆盖了受保护的/gallery路径,根路径/对应的登录路由没有做已登录状态的校验:

  • ProtectedRoute的逻辑是「访问受保护路径时,未登录才跳转到登录页」,但没有限制「已登录状态下不能访问登录页」
  • 所以当你已经有token的情况下手动访问/,路由直接命中exact path="/"的规则,直接渲染登录组件,不会触发任何重定向逻辑

解决方案

封装一个仅未登录状态可访问的公开路由组件,用来包裹登录页这类不需要鉴权的页面,逻辑和ProtectedRoute相反:已登录时跳转到/gallery,未登录才渲染对应组件。

步骤1:新增PublicRoute组件

新建PublicRoute.js文件,代码如下:

import React from "react";
import { Redirect, Route } from "react-router-dom";

function PublicRoute({ component: Component, ...restOfProps }) {
    const isAuthenticated = localStorage.getItem("token");
    return (
        <Route
            {...restOfProps}
            render={(props) =>
                !isAuthenticated ? <Component {...props} /> : <Redirect to='/gallery' />
            }
        />
    );
}
export default PublicRoute;

步骤2:修改App.js的路由配置

把原来根路径的Route替换成PublicRoute即可:

import ReactDOM from 'react-dom';
import LoginSignUp from "./LoginSignUp/LoginSignUp";
import Gallery from "./Gallery/Gallery";
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import ProtectedRoute from "./ProtectedRoute/ProtectedRoute";
import PublicRoute from "./PublicRoute/PublicRoute"; // 引入新增的PublicRoute

function App() {
    return (
        <>
            <Switch>
                {/* 替换原来的Route为PublicRoute */}
                <PublicRoute exact path="/" component={LoginSignUp} />
                <ProtectedRoute component={Gallery} path='/gallery'/>
            </Switch>
        </>
    );
}

if (document.getElementById("main")) {
    ReactDOM.render(<Router><App/></Router>, document.getElementById("main"));
}

修改完成后即可实现预期效果:

  • 未登录时访问/gallery会自动跳转到登录页
  • 已登录时访问/会自动跳转到/gallery页,无法直接进入登录页

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 03:45:04