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

React:如何实现表单数据提交成功后刷新/重定向至首页?

问题解决

你的代码问题在于window.location.href = "/"在发起请求后立即执行,浏览器会中断未完成的POST请求,导致数据提交失败。要确保数据成功插入后再跳转,需把跳转操作放到请求的成功回调里:

修改后的代码:

handleSubmit(event) {
  event.preventDefault();
  const Category_ID = this.props.key_id;
  const CategoryName = this.state.CategoryName;
  const data = {
    Category_ID,
    CategoryName
  };

  fetch(REQUEST_URL, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: { 'Content-Type': 'application/json' }
  })
  .then(response => {
    if (!response.ok) {
      throw new Error('请求失败');
    }
    return response.json();
  })
  .then(() => {
    // 请求成功完成后再执行跳转
    window.location.href = "/";
  })
  .catch((error) => {
    console.log("error in posting data", error);
    // 可在此添加错误提示,比如 alert('数据提交失败,请重试')
  });
}

改动说明:

  • 将跳转逻辑移至then回调内,确保POST请求成功完成后才触发页面跳转
  • 新增response.ok判断,处理HTTP状态码异常(如4xx/5xx错误)的情况
  • 完善错误捕获的信息输出,便于排查问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:27:36