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

React登录认证跳转异常求助:认证成功无法进入目标资源列表页

问题分析与解决方案

核心问题

  1. 登录成功后无跳转:当前登录逻辑仅完成token存储,未触发页面导航动作,Router无法感知认证状态变化。
  2. 错误密码时异常跳转:登录请求异步执行过程中,未等待结果就可能触发错误的页面导航(或Guard的同步检查逻辑存在时序问题)。

分步修复

1. 登录成功后添加导航逻辑

修改Login组件,使用useNavigate在登录成功后手动跳转到首页:

import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import LoginView from "./view";
import { AuthService } from "../../services/auth.services";

function Login() {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  async function onSubmit({ username, password }) {
    try {
      // 等待登录请求完成,unwrap获取成功结果
      await dispatch(AuthService.userLogin({ username, password })).unwrap();
      // 登录成功后跳转到首页
      navigate("/");
    } catch (error) {
      // 登录失败,可在此添加错误提示逻辑
      console.error("登录失败:", error);
    }
  }

  return <LoginView onSubmit={onSubmit} />;
}

export default Login;

2. 修复Auth Slice状态错误

authSlice中fulfilled回调错误修改了pending状态,应改为isLoading:

.addCase(AuthService.userLogin.fulfilled, (state, { payload }) => {
  state.isLoading = false; // 修正为isLoading
  state.data = payload;
})

3. 优化AdminGuard的认证检查逻辑

当前Guard仅在组件挂载时检查一次认证状态,当localStorage中的token变化时无法自动更新。添加监听逻辑确保状态同步:

import React, { useEffect, useState } from "react";
import { Navigate } from "react-router-dom";
import { AuthService } from "../services/auth.services";

const AdminGuard = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(AuthService.isAuthenticated());

  useEffect(() => {
    const handleStorageUpdate = () => {
      setIsAuthenticated(AuthService.isAuthenticated());
    };

    // 监听localStorage变化
    window.addEventListener("storage", handleStorageUpdate);
    // 组件挂载时再次确认状态
    setIsAuthenticated(AuthService.isAuthenticated());

    return () => window.removeEventListener("storage", handleStorageUpdate);
  }, []);

  return isAuthenticated ? children : <Navigate to="/login" replace />;
};

export default AdminGuard;

4. 修复Axios请求格式错误

AuthService中的axios请求重复设置了请求体,移除config中的body字段:

const response = await axiosApiInstance.post(
  "https://localhost:7105/api/Connect",
  { 
    username: typeof username === "string" ? username.toString() : "",
    password: typeof password === "string" ? password.toString() : ""
  },
  {
    headers: {
      "Content-Type": "application/json",
    },
  }
);

效果验证

  • 登录成功后将自动跳转到/资源列表页
  • 输入错误密码时,登录请求失败,不会触发页面跳转
  • 认证状态变化时,AdminGuard会自动同步并正确控制页面访问权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 05:17:08