React类组件Axios响应后路由跳转失败:navigate不是函数
问题场景
我有一个表单类组件,通过Axios向数据库提交数据,希望在Axios响应获取到ID后,携带该ID进行路由跳转,但一直报错TypeError: this.props.navigate is not a function。由于类组件无法使用useNavigate(),useHistory已废弃且不想降级React,尝试通过高阶组件传递navigate仍无法正常工作。
类组件内的handleSubmit方法代码
handleSubmit(e){ e.preventDefault(); console.log("SUBMITTED") const formData = new FormData(); formData.append('title',this.state.title); formData.append('description',this.state.description); formData.append('author',this.state.author); formData.append('hashtags',this.state.hashtags); formData.append('file',this.state.file); axios.post('http://localhost:8002/upload',formData,{}) .then(res=>{ this.setState({id:res.data.zineCreated._id}) console.log(res.data.zineCreated._id) console.log(res) //history let path = '/viewmyzine/62e0b9d44d0be19bd9e84bd5'; this.props.navigate(path); //not working // this.props.navigation.navigate('/viewmyzine/62e0b9d44'); //not working }) }
尝试的高阶组件代码
function WithNavigate(props) { let navigate = useNavigate(); return <ViewZine test="NAGIVATE" navigate={navigate} /> }
问题原因及修复方案
核心问题
你没有将包裹后的高阶组件WithNavigate注册到路由中,而是直接注册了原始的ViewZine组件。React Router仅会为直接配置在<Route>内的组件注入路由相关能力,同时你的高阶组件没有传递自身接收的所有props,可能导致其他必要参数丢失。
修复步骤
修改高阶组件,传递完整props
确保将高阶组件接收的所有props传递给ViewZine:function WithNavigate(props) { const navigate = useNavigate(); // 展开所有props并附加navigate return <ViewZine {...props} navigate={navigate} />; }更新路由配置
在路由配置中,将原来的ViewZine替换为WithNavigate:// 示例路由配置 import { Route, Routes } from 'react-router-dom'; import WithNavigate from './path-to-your-component'; function AppRoutes() { return ( <Routes> {/* 替换为包裹后的组件 */} <Route path="/your-form-route" element={<WithNavigate />} /> <Route path="/viewmyzine/:id" element={<ViewMyZine />} /> </Routes> ); }优化跳转逻辑(可选)
用接口返回的真实ID拼接跳转路径,避免写死:.then(res=>{ const newZineId = res.data.zineCreated._id; this.setState({id: newZineId}); // 使用真实ID跳转 this.props.navigate(`/viewmyzine/${newZineId}`); })
内容的提问来源于stack exchange,提问作者deathloser
相关产品推荐
相关产品推荐

