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

React中useNavigate与HOC组件配合失效,登录后无法跳转

登录成功后navigate不跳转问题的解决方案

1. React Router v6 路由保护写法不兼容

你当前的HOC写法在React Router v6里存在适配问题,导致跳转后路由保护逻辑异常,页面无法正常渲染。

修改Protect组件:改成包裹子组件的形式,同时处理加载状态避免初始跳转闪烁:

import React, { useState, useEffect } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import axios from 'axios';

const Protect = ({ children }) => {
  const [authenticated, setAuthenticated] = useState(null);
  const location = useLocation();

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const response = await axios.get('http://localhost:5000/checkAuth', { withCredentials: true });
        console.log('Protected GET Response:', response.data);
        setAuthenticated(response.status === 200);
      } catch (error) {
        console.error('Protect: Error during auth', error.response);
        setAuthenticated(false);
      }
    };

    checkAuth();
  }, []);

  if (authenticated === null) {
    return <div>加载中...</div>;
  }

  return authenticated ? children : <Navigate to="/Login" state={{ from: location }} replace />;
};

export default Protect;

更新App.js路由配置:用Protect直接包裹ProtectedPage,而非通过component属性传递:

<Route
  path="/ProtectedPage"
  element={
    <Protect>
      <ProtectedPage />
    </Protect>
  }
/>

2. 后端接口响应逻辑错误

你的/checkAuth接口里res.sendStatus(200).send(...)写法有问题:sendStatus会直接发送状态码并结束响应,后续的send完全不会执行,前端拿不到预期的响应数据,可能间接导致路由保护判断异常。

修复后端代码:

app.get('/checkAuth', verifyToken, (req, res) => {
  res.status(200).send({ authenticated: true, email: req.email, token: req.token });
});

3. 确认navigate函数的正确获取

确保FormLogin组件里正确通过useNavigate钩子拿到navigate函数:

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

const FormLogin = () => {
  const navigate = useNavigate();

  const handleFormSubmit = async (event) => {
    // ... 原有登录逻辑
    navigate('/ProtectedPage', { replace: true }); // 用replace避免登录页留在历史栈,返回时直接回到之前的页面
  };
};

4. 排查路由冲突

检查App.js里有没有重复定义/ProtectedPage路由,或者确保更具体的路由(比如/ProtectedPage)放在通用动态路由(比如/:id)前面,避免路由匹配优先级错误。


内容的提问来源于stack exchange,提问作者Francesco Lo Verde

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:53:20