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

使用useNavigate调用history.go()报错:history.go不是函数的解决方法

解决React Router useNavigate钩子调用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 05:52:43