简体   繁体   English

Reactjs:表单操作方法和onSubmit

[英]Reactjs: Form action method and onSubmit

I have a situation where I need to submit my form. 我有一种情况需要提交表格。 When I use this method 1 当我使用这种方法时1

Method 1

<form action="my_redirect_url" method="post" onSubmit={this.registerEmail.bind(this)}>
   <input
     type="text"
     placeholder='Email address'
     name='EMAIL'
     value={this.state.email}
     onChange={this.handleChangeEmail}
   />
   <button type='submit' />
</form>

Then the form submits perfectly but I miss the form validation ie the email validation part. 然后表单提交完美,但我错过了表单验证,即电子邮件验证部分。 Its valid or not, the form redirects 它的有效与否,表格重定向

Method 2

// onSubmit method
registerEmail = (e) => {
  e.preventDefault();
  let { email } = this.state;
  let emailValidated = validateEmail(email);
  if (emailValidated) {
    fetch('my_redirect_url', {
      method: 'post',
      body : JSON.stringify({
        EMAIL: email
      }),
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    .then(ParseJSON) // It parses the output
    .catch(function(error) {
      console.log("error---", error)
    });
  } else {
    alert("invalid email")
  }
}

// Form
<form onSubmit={this.registerEmail.bind(this)}>
   <input
     type="text"
     placeholder='Email address'
     name='EMAIL'
     value={this.state.email}
     onChange={this.handleChangeEmail}
   />
   <button type='submit' />
</form>

In Method 2, the validation is done correctly but then it doesnot redirects and says an error that Fetch api cannot load 'my_redirect_url' Response for preflight is invalid (redirect) 在方法2中,验证正确完成,但它没有重定向,并说Fetch api cannot load 'my_redirect_url' Response for preflight is invalid (redirect)的错误Fetch api cannot load 'my_redirect_url' Response for preflight is invalid (redirect)

So whats the issue and how can it be solved? 那么问题是什么,如何解决?

If you tell the program to e.preventDefault() , then he won't execute the normal redirect, which we are all waiting for. 如果你告诉程序e.preventDefault() ,那么他将不会执行我们都在等待的正常重定向。

So vice versa you have to remove it to redirect the user afterward. 反之亦然,您必须将其删除以便以后重定向用户。 Only preventDefault() if the E-Mail is incorrect. 如果电子邮件不正确,则只有preventDefault()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM