TypeError:无法读取ContactComponent.js中未定义的属性“ firstname”

时间:2020-07-09 04:27:02

标签: javascript reactjs frontend jsx

Contact.render

F:/React/confusion/src/components/ContactComponent.js:133

<Input type="text" id="firstname" name="firstname"
  placeholder="First Name"
  value={this.state.firstname}
  valid={errors.firstname === ''}
  invalid={errors.firstname !== ''}
  onBlur={this.handleBlur('firstname')}
  onChange={this.handleInputChange} />

github:https://github.com/KhushalAbrol/KhushalAbrol--Ristorante-Con-Fusion-React-

请告诉我为什么会出现此错误?

1 个答案:

答案 0 :(得分:0)

问题

您正在第133行访问未定义对象的某个值firstname,即errors 必须 。沿着小路走...

valid={errors.firstname === ''}

您不会从validate函数返回errors,因此在line 82上未定义它。

const errors = this.validate(
  this.state.firstname,
  this.state.lastname,
  this.state.telnum,
  this.state.email
);

解决方案

在验证功能的末尾返回errors

validate(firstname, lastname, telnum, email) {
    const errors = {
        firstname: '',
        lastname: '',
        telnum: '',
        email: '',
    };

    if (this.state.touched.firstname && firstname.length <=3)
        errors.firstname = 'First Name should be >=3 characters'
    else if (this.state.touched.firstname && firstname.length >=10)
        errors.firstname = 'First Name should be <=10 characters'

    if (this.state.touched.lastname && lastname.length <=3)
        errors.lastname = 'Last Name should be >=3 characters'
    else if (this.state.touched.lastname && lastname.length >=10)
        errors.lastname = 'Last Name should be <=10 characters'

    const reg = /^\d+$/;
    if (this.state.touched.telnum && !reg.test(telnum))
        errors.telnum = 'Last Name should contain only '
    
    if (this.state.touched.email && email.split('').filter(x => x === '@').length !==1)
        errors.email = 'mail should contain a \'@\' '

    return errors; // <-- return errors object for consumption
}

建议

遇到错误时,请阅读所有消息,它们通常包括行号和堆栈跟踪,并告诉您问题出在哪里。这就是他们的目的。请同时附上您的相关代码 IN 您的问题,因为git repos可能会发生变异或时间变化,甚至会完全迁移,但此代码应包含在此处,以供将来的读者使用。 / p>