1

大家好,我在使用反应钩子验证表单时遇到了一些问题。每当我单击提交按钮时,我都会收到错误消息

index.js:1 警告:组件正在将电子邮件类型的受控输入更改为不受控制。输入元素不应从受控切换到不受控(反之亦然)。决定在组件的生命周期内使用受控输入元素还是不受控输入元素。

这是我的代码。

    const [formData, setFormData] = useState({
  email:'',
  password:'',
  emailError:'',
  passwordError:''
 }) 



 const handleEmailChange = e => setFormData({email: e.target.value})

 const handlePasswordChange = e => setFormData({password: e.target.value})

 //validate
 const validate = () => {
  let inputError = false
  const errors = {
   emailError:'',
   passwordError:''
  }
  if(!formData.email) {
   inputError = true
   errors.emailError = 'Please enter a valid email'
  } 
  else if(!formData.email.match(emailRegex)) 
  {
   inputError = true
   errors.emailError = (
    <span style={{color:'red'}}>Your email address must be valid</span>
   )
  }

  if(formData.password.length < 4){ 
   inputError = true
   errors.passwordError = 'Your password must contain more than 4 characters'
  }

  setFormData({
   ...errors
  })

  return inputError
 }

 const onSubmit = e => {
  e.preventDefault();

  const err = validate();

  if(!err){`
   setFormData(formData)
  }
 }

我的 JSX

   <FormContainer>
   <div className="form-container">
    <form >
     <h1>Sign in</h1>
     <div className="input-container">
      <input className={formData.emailError ? 'input-error input-empty' : 'input-empty'}
       value={formData.email} 
       type="email"
        required
        onChange={e => handleEmailChange(e)}
        />
      <label>Email or Phone Number</label>
      <span style={{color: '#db7302'}}>{formData.emailError}</span>
     </div>
     <div className="input-container">
      <input 
      className={formData.passwordError ? 'input-error input-empty' : 'input-empty'}
       type="password" 
       value={formData.password} 
       required
       onChange={e => handlePasswordChange(e)}
       />
      <label>Password</label>
      <span style={{color: '#db7302'}}>{formData.passwordError}</span>
     </div>
     <div className="input-container">
      <Button href="/" onClick={e => onSubmit(e)} type="submit">Sign in</Button>
     </div>
     <label className="checkbox-container">
      Remember me
     <input type="checkbox" checked />
      <span className="checkmark"></span>
     </label>
     <Link to="/" className="need-help">Need Help?</Link>
     <div className="bottom-form">
      <img src={fbLogo} alt="" />
      <Link to="/" className="login-fb">
       Login with facebook
     </Link>
     <br/>
     <br/>
     <span style={{color:'#999'}}>New to netflix?</span>&nbsp;
     <Link to="/" className="signup-txt">Sign up now</Link>
     </div>
    </form>
   </div>
  </FormContainer>
4

1 回答 1

1

当您设置 时formData,您不会包含所有值,因此它不是email作为空字符串,而是变为undefined,并且 React 决定 aninput不受控制,如果它的值是undefined

为防止这种情况,请在设置时包含表单的先前值formData

setFormData(formData => ({
  ...formData,
  ...errors
}))
于 2020-04-14T14:42:42.007 回答