如果表单中的一个输入错误,则会打印所有错误消息-React Form

时间:2019-07-16 04:08:52

标签: reactjs forms error-handling jsx

我目前正在通过检查response.status是否失败来显示有关提交的错误消息,但是我不确定如何为每个错误进行映射,并且即使只有一个输入错误,我也正在打印所有错误消息。我一直想显示绿色的“您的消息已发送!”一切正确并提交后,在基本

标记中输入文本。

我尝试映射错误字段,但不确定如何正确执行操作。我正在尝试使用error.field ==='fullName',我认为可以。

class Contactus extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      form: {
        fullName: null,
        email: null,
        subject: null,
        message: null,
      },
      formErrors: {
        name: "",
        email: "",
        subject: "",
        message: "",
      }
    }
    this.onSubmit = this.onSubmit.bind(this)
  }
  onSubmit() {

    const { form } = this.state

    Http.post('/contact-form', { data: form }).then((response) => {
      console.log(response)

      if (response.status === 'failed') {
        this.setState({ formErrors: { name: 'error message' } })

        const errors = response.data.errors
        errors.map((error, key) => {
          error.field === 'fullName'
        }
        )
      }

    }).catch((error) => {
      console.log(error)
    })
  }

....

render() {
    const props = this.props
    const { form } = this.state
    const { formErrors } = this.state
    return (
      <React.Fragment>

        <div id="contact-us" className="container">
          <div className="row background-image">
            <div className="form col-xs-10 col-xs-offset-1 col-sm-6 col-md-6 col-lg-5">
              <form onSubmit={(e) => { e.preventDefault(); this.onSubmit(); }}>
                <h1>Contact Us</h1>
                <p>Use the contact below to get in touch with the team at the Front. We’d love to hear from you!<br />
                  <br />
                  <strong>Please note: We don’t take bookings via this website or a phone call.</strong></p>
                <span>
                  {formErrors.name !== '' && <p>Please enter Name</p>}
                </span>
                <label>
                  Full Name:
                  <input type="text" className="" name="name" placeholder="John Doe" onChange={(e) => { this.setState({ form: { ...form, fullName: e.target.value } }) }} />
                </label>
                <p></p>
                <span>
                  {formErrors.email !== '' && <p>Please enter valid email address</p>}
                </span>

...

当前,我在上方的表单输入中以红色

即时打印上述所有错误消息。

2 个答案:

答案 0 :(得分:0)

查看您的代码后,我发现了2个问题。

  1. 您只需要替换状态中的整个formErrors对象,即使用以下命令后现有值会丢失:this.setState({ formErrors: { name: 'error message' } })相反,您应该使用this.setState({formErrors: { ...this.state.formErrors, name: 'error message' } })
  2. 在代码this.setState({ formErrors: { name: 'error message' } })中执行此行后,电子邮件将变为undefined,而不是<blank>,并且您正在检查{formErrors.email !== '' && <p>Please enter valid email address</p>}中的空白条件:为名字。相反,您应该使用{!!formErrors.email && <p>Please enter valid email address</p>}

在上面进行修复后,您的代码将正常运行。

答案 1 :(得分:0)

好的,我解决了这一问题,只是删除了

// const errors = response.data.errors
// errors.map((error, key) => {
//   error.field === ''
// }
// )

并添加:

if (response.status === 'failed' && response.data.errors[0].field === "fullName") {
        this.setState({ formErrors: { ...this.state.formErrors, name: 'error message' } })
        return

      } else if (response.status === 'failed' && response.data.errors[0].field === "email") {
        this.setState({ formErrors: { ...this.state.formErrors, email: 'error message' } })
        return