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
相关产品推荐
相关产品推荐

