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

React类组件SubmitHandler提交后无法跳转至Dashboard问题排查

问题原因

你使用的是React Router v6,该版本不再自动向路由组件传递history、location等路由相关props。因此this.props.history是undefined,调用push方法时触发错误,导致代码进入catch分支弹出错误提示,同时导航到Dashboard的逻辑无法执行。不过axios的POST请求已经成功发送到后端,所以数据库里的数据能正常更新。

解决方案

下面提供两种可行的修复方式:

方式一:用高阶组件注入导航功能

  1. 创建一个高阶组件withNavigate,用来给类组件传递navigate函数:
import { useNavigate } from 'react-router-dom';
import React from 'react';

const withNavigate = (Component) => {
  return (props) => {
    const navigate = useNavigate();
    return <Component {...props} navigate={navigate} />;
  };
};
  1. 修改CreateMonthWallet组件的导出语句,用这个高阶组件包裹:
export default withNavigate(CreateMonthWallet);
  1. 更新submitHandler里的导航代码:
.then((res) => {
    this.props.navigate('/Dashboard');
})

方式二:直接从App组件传递navigate函数

  1. 在App组件中获取navigate函数并传递给CreateMonthWallet:
import { Router, Routes, Route, useNavigate } from 'react-router-dom';

function App() {
    const navigate = useNavigate();
    return (
        <Router>
            <div>
                <Nav />
                <Routes>
                    <Route path="/" element={<Welcome />} exact />
                    <Route path="/Dashboard" element={<Dashboard />} exact />
                    <Route path="/CreateMonthWallet" element={<CreateMonthWallet navigate={navigate} />} exact />
                    <Route path="*" element={<NotFound />} exact />
                </Routes>
            </div>
        </Router>
    )
}
  1. 同样修改submitHandler中的导航逻辑为:
this.props.navigate('/Dashboard');
额外优化建议
  • 将event.preventDefault()移到submitHandler的最开头,避免表单默认提交导致页面刷新:
submitHandler = (event) => {
    event.preventDefault(); // 先阻止默认提交行为
    const newWallet = {
        name: this.state.name,
        accountNumber: this.state.accountNumber,
        description: this.state.description,
        priority: this.state.priority
    }
    axios.post('http://localhost:8080/monthwallet', newWallet)
        .then((res) => {
            this.props.navigate('/Dashboard');
        }).catch((err) => {
            console.error('请求错误详情:', err); // 打印错误信息方便排查
            alert(`错误:${err.message}`);
        })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:00:56