【问题标题】:react js form getting submitted twice反应js表单提交两次
【发布时间】:2022-01-05 11:46:34
【问题描述】:

我有以下调用保存表单的代码

           <div className="col-md-4">
              <button onClick={saveCredit}  className="btn btn-success">
                Submit
            </button>

我有 onclick 处理函数

 const saveCredit = () =>{
     //validate form
     // call api to save form attributes
     CreditTransactionDataService.create(data)
    .then(response => {
      setSubmitted(true);
      console.log(response.data);
    })
    .catch(e => {
      console.log(e);
    });

 }

成功保存后,我会显示成功信息如下。

{submitted ? (
        <div>
          <h4>You submitted successfully!</h4>
          <button className="btn btn-success mr-2" onClick={newCreditTransaction}>
            Add
          </button><Link style={{ fontWeight: 'bold' }} className="btn btn-warning" to={"/creditTransactionList"}>
            return to List
          </Link>
        </div>
      )

但问题是,我的表单被提交了两次,并创建了具有相同值的重复记录....几个保存选项,我在数据库级别使用唯一键列进行了限制,但仍然需要在代码中处理很少的表等级..

【问题讨论】:

  • 您的表单是否包含onSubmit,因为如果包含,那么当您单击提交按钮时它将被调用两次,因为您也在onClick中调用它
  • 我的表单中没有 onSubmit .. 我在按钮标签中只有 onClick 处理程序
  • saveCredit 是一个块,不应该是一个函数吗?

标签: html jquery reactjs spring-boot


【解决方案1】:

我无法在 codepen 中重现它,但是如果已经提交了一个有点 hacky 的解决方案,可以在方法中检查它

 const saveCredit = {
     //Check if it is submitted
     if(!submitted){
     //validate form
     // call api to save form attributes
     CreditTransactionDataService.create(data)
    .then(response => {
      setSubmitted(true);
      console.log(response.data);
    })
    .catch(e => {
      console.log(e);
    });
   }
 }

这可能不是最好的,但可以完成这项工作

我还注意到,你的 saveCredit 函数看起来不像一个函数。

为什么不声明为箭头函数?喜欢:

const saveCredit = () => { //Your code }

【讨论】:

  • 这是错字...现在更正
  • 您是否怀疑链接块再次提交表单?
【解决方案2】:

如果您的按钮负责提交某个表单,则它不需要onClick 事件处理程序。您应该将type="submit" 添加到button 并将onSubmit 添加到form 标记本身。

您应该采用这种方法来正确处理提交(包括点击按钮或用户按回车键)。

【讨论】:

    猜你喜欢
    • 2016-08-27
    • 2011-06-17
    • 2021-06-19
    • 1970-01-01
    • 2013-03-27
    • 2014-11-03
    • 2015-04-04
    • 2017-08-29
    • 1970-01-01
    相关资源
    最近更新 更多