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

使用window.location无法跳转至/SignIn仅URL加?,求教history.push用法

跳转失效问题原因
  • 核心原因是你注释了表单默认行为阻止代码:e.preventDefault(),表单触发submit事件后会执行默认的提交逻辑,默认会以GET方式重载当前页面,将表单参数拼接在URL后缀,无参数时就会出现你看到的/updateinfo?格式的URL。默认提交逻辑执行优先级高于axios异步回调,导致回调内的跳转代码还没执行,页面就已经被刷新重置,跳转自然不生效。
  • 次要问题:window.location直接赋值属于非标准写法,部分浏览器存在兼容性问题,标准写法是赋值给window.location.href属性。
修复后的代码示例
onSubmit(e){
    // 取消注释,阻止表单默认提交行为
    e.preventDefault();
    console.log("1")
    const user = {
        Name : this.state.Name,
        Email : this.state.Email,
        Password : this.state.Password,
        Type : this.state.Type
    }
    console.log(user)
    console.log("1")
    axios.post('http://localhost:8000/Updateinfo', user)
    .then(res=>{
        // 标准跳转写法
        window.location.href = '/SignIn';
    })
    .catch(err=>{
        // 补充错误捕获,避免接口报错时无反馈
        console.error('更新信息失败:', err)
    })
    // 这行日志先打印是正常现象,axios.post是异步操作,回调晚于同步代码执行
    console.log("didn't redirect !");
}
history.push 正确使用方法

history.push是单页应用前端路由的跳转方式,优势是不会触发整页重载,性能优于window.location跳转,仅适用于同SPA应用的内部路由跳转,跨域跳转、需要整页刷新的场景不适用。

  • React Router v5 用法
    • 类组件:使用withRouter高阶组件包裹组件后,直接从props获取history对象调用:this.props.history.push('/SignIn')
    • 函数组件:使用useHistory钩子获取实例
    import { useHistory } from 'react-router-dom';
    function UpdateInfo() {
      const history = useHistory();
      // 跳转时调用
      const goSignIn = () => history.push('/SignIn');
    }
    
  • React Router v6 用法
    v6版本移除了useHistory,替换为useNavigate钩子,用法如下:
    import { useNavigate } from 'react-router-dom';
    function UpdateInfo() {
      const navigate = useNavigate();
      // 跳转时调用
      const goSignIn = () => navigate('/SignIn');
      // 等价于history.go(-1) 返回上一页的写法:navigate(-1)
    }
    
  • 注意:所有路由相关方法的使用前提是,组件处于Router组件的上下文包裹范围内,否则无法读取路由实例会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:06:03