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

类组件调用useNavigate报错,求Axios请求后页面跳转方案

解决React Hook不能在类中调用的问题

报错的核心原因是useNavigate是React Hook,只能在函数组件或自定义React Hook中调用,不能用在普通类里。以下是两种可行的修改方案:

方案一:将网络请求逻辑改为自定义Hook

直接把原有的类改成自定义Hook,这样就能合法使用useNavigate:

import axios from "axios";
import { useNavigate } from "react-router-dom";

export function useEmployeeNetworking() {
  const navigate = useNavigate();

  const authentication = async (email: string, password: string) => {
    try {
      const response = await axios.post("http://localhost:3000/login", {
        email,
        password
      });
      console.log(response);
      navigate("/dashboard");
    } catch (errors) {
      console.log(errors);
    }
  };

  return { authentication };
}

在登录函数组件中使用这个Hook:

import { useEmployeeNetworking } from './path-to-your-hook-file';
import { useState } from 'react';

function LoginComponent() {
  const { authentication } = useEmployeeNetworking();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = async () => {
    await authentication(email, password);
  };

  return (
    <div>
      <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
      <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
      <button onClick={handleLogin}>登录</button>
    </div>
  );
}

方案二:分离网络请求与导航逻辑

让EmployeeNetworking类只负责网络请求,返回Promise,导航逻辑交给调用它的函数组件处理:

修改网络请求类:

import axios from "axios";

export class EmployeeNetworking {
  static async authentication(email: string, password: string) {
    try {
      const response = await axios.post("http://localhost:3000/login", {
        email,
        password
      });
      console.log(response);
      return response;
    } catch (errors) {
      console.log(errors);
      throw errors; // 抛出错误,让组件处理失败场景
    }
  }
}

在登录函数组件中处理导航:

import { useNavigate } from "react-router-dom";
import { EmployeeNetworking } from './path-to-your-networking-file';
import { useState } from 'react';

function LoginComponent() {
  const navigate = useNavigate();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = async () => {
    try {
      await EmployeeNetworking.authentication(email, password);
      navigate("/dashboard");
    } catch (err) {
      // 这里可以添加登录失败的提示逻辑,比如弹窗提示用户账号密码错误
    }
  };

  return (
    <div>
      <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
      <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
      <button onClick={handleLogin}>登录</button>
    </div>
  );
}

两种方案任选其一即可:方案一适合把请求和导航逻辑封装在一起,方案二更符合职责分离的原则,网络层只处理数据交互,组件层处理UI和页面跳转。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:30:47