在react中使用axios响应重定向



我有一个表单class Component,它使用Axios提交到数据库。我想等待Axios的响应,这样我就可以获得ID,然后在路由中使用ID重定向。

我的问题是我一直得到

类型错误:this.props.navigate不是函数

因为useNavigate((不能在Class组件中使用。我尝试使用useHistory,但它已被弃用,不想降级react。

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} />
}

但它仍然不起作用

只有当您有可用的id状态时,才尝试渲染<Navigate>组件。这是医生的建议。

或者,如果您想重新加载页面,可以调用document.location.assign(path)(或window.location.assign(path)(,而不是使用react路由器来处理虚拟位置。。。

然而,我能够得到您的示例的简化版本(不使用Navigate组件(:

import {useNavigate, BrowserRouter, Route, Routes} from 'react-router-dom'
import {Component} from 'react'
export default function App() {
return (
<div className="App">
<h1>Demo</h1>
<BrowserRouter>
<Routes>
<Route path='b' element={<blockquote>(at b)</blockquote>}/>
</Routes>
<NavigateWrapper />
</BrowserRouter>
</div>
);
}
function NavigateWrapper(props) {
const navigate = useNavigate()
return (<NavigateButton navigate={navigate} />)
}
class NavigateButton extends Component {
render() {
return <button onClick={event => this.callNavigate()}>call navigate</button>
}
callNavigate() {
alert(this.props.navigate)
this.props.navigate('b')
}
}

(参见代码沙箱示例(

因此,应该可以将导航作为道具传递给组件元素,并且它应该可以工作。如果这不起作用,我会怀疑回调发生时不再呈现某些内容。。。