首页 > 解决方案 > TypeError:无法读取未定义的属性“名字”,在 ContactComponent.js 中

问题描述

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-

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

标签: javascriptreactjsfrontendjsx

解决方案


问题

您正在访问firstname第 133 行上未定义对象的某些值,即errors 必须未定义。追踪...

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

您不会errors从您的validate函数返回,因此它在第 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
}

建议

当您遇到错误时,请阅读所有消息,它们通常包括行号和堆栈跟踪,并告诉您问题出在哪里。这就是他们的目的。还请在您的问题中包含您的相关代码,因为 git repos 倾向于变异或时间,甚至完全重新定位,但代码应包含在此处以供未来的读者使用。


推荐阅读