提交按钮需要2次点击才能在React中调用函数

提交按钮需要2次点击才能在React中调用函数

本文介绍了提交按钮需要2次点击才能在React中调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我单击提交"按钮时,需要单击以正确启动该功能.在执行if语句之前,我没有任何问题.它是否具有某些事实,即我内部有2条if语句,每次单击后它仅检查1条if语句?

When i'm clicking submit button it requires to clicks to properly fire off the function. I didn't have problem before implementing if statements. Does it have something with fact that i have 2 if statements inside and after each click it checks only 1 if statement?

  onSubmit = (e) => {

const { firstName, lastName, email, eventDate, validation} = this.state

if (firstName, lastName, eventDate, email) {
  this.setState({validation: true})
  if (new RegExp(/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,15}/g).test(email)) {
    this.setState({validation: true})
  } else {
    this.setState({validation: false})
    this.setState({errorMessage: 'Please enter correct email adress'})
  }
} else {
  this.setState({validation: false});
  this.setState({errorMessage: 'Please fill in all fields properly'})
}

if (validation) {

  const newEvent = {
    firstName: this.state.firstName,
    lastName: this.state.lastName,
    email: this.state.email,
    eventDate: this.state.eventDate
  }

  this.props.addEvent(newEvent);

  this.setState({
    firstName: '',
    lastName: '',
    email: '',
    eventDate: '',
    validation: false,
    errorMessage: ''
  });
}

e.preventDefault();
}

推荐答案

解决了此问题,他们成功的关键是将if(validation)语句主体移到setState的回调函数中.

Fixed this issue, they key to success was moving my if(validation) statement body to callback function of setState.

这是工作代码:

  onSubmit = (e) => {
const { firstName, lastName, email, eventDate, validation} = this.state

if (firstName, lastName, eventDate, email) {
  this.setState({validation: true})
  if (new RegExp(/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,15}/g).test(email)) {
    this.setState({validation: true}, () => {
      const newEvent = {
        firstName: firstName,
        lastName: lastName,
        email: email,
        eventDate: eventDate
      }
      this.props.addEvent(newEvent);

      this.setState({
        firstName: '',
        lastName: '',
        email: '',
        eventDate: '',
        validation: false,
        errorMessage: ''
      })
    })
  } else {
    this.setState({validation: false, errorMessage: 'Please enter correct email adress'})
  }
} else {
  this.setState({validation: false, errorMessage: 'Please fill in all fields properly'})
}
e.preventDefault();
}

这篇关于提交按钮需要2次点击才能在React中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:09