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

React表单提交按钮点击后页面刷新且fetch请求失效问题求助

解决React表单提交时页面刷新、fetch请求未执行的问题

问题根源

你当前把提交逻辑绑定在<input type="submit">的onClick事件上,虽然调用了event.preventDefault(),但浏览器触发表单默认提交行为的时机是在按钮点击之后的表单submit事件,仅在按钮点击事件里阻止默认行为可能无法拦截表单的提交刷新。

修复方案

将提交逻辑绑定到<form>标签的onSubmit事件上,直接阻止表单的默认提交行为,这是处理表单提交的标准方式。

修改后的表单代码

<form onSubmit={submit}>
  <div id="jn">
    <div id="inps">
      <input type="number" className='si' id="mdinp" onChange={formChangeID} placeholder='Enter Id' />
      <br />
      <input type="password" className='si is' id="mdinp2" onChange={formChangePASS} disabled placeholder='Enter Password' />
      <br />
      <input type="submit" id='mdg' value="GO!" disabled />
    </div>
  </div>
</form>

修改后的提交函数

const submit = (event) => {
  // 只需要一次preventDefault即可阻止表单默认提交
  event.preventDefault();
  fetch('http://localhost:3001/quizInfo',{
    method: 'POST',
    mode: 'cors', 
    cache: 'no-cache',
    credentials: 'same-origin', 
    headers: {
      'Content-Type': 'application/json'
    },
    redirect: 'follow', 
    referrerPolicy: 'no-referrer',
    body: JSON.stringify({
      ID: GameId
    })
  })
  .then(res => res.json())
  .then(data => console.log(data[0].ques1))
  // 建议添加错误捕获,方便排查请求问题
  .catch(error => console.error('请求失败:', error));
}

额外提示

  • 移除按钮上的onClick={submit}绑定,避免逻辑重复触发
  • 确保GameId变量已正确定义并获取到输入框的值
  • 添加catch块可以帮你快速定位fetch请求是否存在其他错误(比如跨域、后端接口问题等)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:55:16