使用useNavigate调用history.go()报错:history.go不是函数的解决方法
你在使用React Router的useNavigate钩子时,将其赋值给history常量后调用history.go(-1),出现了如下错误:
Unhandled Rejection (TypeError): history.go is not a function
你的代码如下:
const history = useNavigate() const handleSubmit = (e) => { e.preventDefault() // default action of form submission is to refresh the page const blog = { title, body, author } setIsPending(true) // should work only after the handleSubmit() event occurs fetch('http://localhost:8000/blogs', { method: 'POST', headers: {"Content-Type": "application/json"}, body: JSON.stringify(blog) }).then(() => { console.log('New blog added') setIsPending(false) history.go(-1) }) }
解决方案
- React Router v6的
useNavigate返回的函数没有go()方法,它的API和旧版history对象不同。要实现返回上一页,直接调用该函数并传入数字-1即可。 - 若要跳转到指定路由,直接传入目标路径字符串,比如
navigate('/blogs')。
修改后的代码示例:
const navigate = useNavigate() // 建议变量名改为navigate,避免和旧版history对象混淆 const handleSubmit = (e) => { e.preventDefault() const blog = { title, body, author } setIsPending(true) fetch('http://localhost:8000/blogs', { method: 'POST', headers: {"Content-Type": "application/json"}, body: JSON.stringify(blog) }).then(() => { console.log('New blog added') setIsPending(false) navigate(-1) // 直接传入-1实现返回上一页 }) }
补充说明:
useNavigate返回的函数支持两种参数:数字表示前进/后退的步数(-1=上一页,1=下一页);字符串表示目标路由路径。- 把变量名从
history改为navigate是为了更贴合钩子的语义,减少概念混淆。
内容的提问来源于stack exchange,提问作者Nishtha Barnwal
相关产品推荐
相关产品推荐

