在遍历数组时从状态访问值时遇到问题

时间:2019-05-29 11:57:33

标签: javascript reactjs

我正在尝试遍历数组并执行一些操作。但是无法按我想要的方式访问值。

inputObj.map(el => {
    const msg = this.state.validation[el.id].message;
    const msg2 = this.state.validation['name'].message;
})

此处,el.id可以是namedobaddress。当我使用this.state.validation[el.id].message;时,它显示TypeError: Cannot read property 'message' of undefined。但是,如果我像this.state.validation['name'].message;这样硬编码,它就可以正常工作。比较el.id'name'时,它们具有相同的数据类型和相同的值。因此,为什么在使用el.id而不是对其进行硬编码时遇到问题。

注意:我正在使用reactjs

编辑:

此状态:

this.state = {
    super(props);
    this.validator = new FormValidator([
        {
            field: 'name',
            method: 'isEmpty',
            validWhen: false,
            message: 'Name is required'
        },
        ...
    ]);

    orderForm: {
        name: {
             elementType: 'input',
             elementConfig: ''
        },
        ...
    }

    validation: this.validator.setValid() // it will be the updated upon submitting form on submitHandler by calling validate() from FormValidator
}

inputObj:

   const inputObj= [];
   for(let key in this.state.orderForm){
       inputObj.push({
           id : key,
           config: this.state.orderForm[key]
       });
   }

FormValidator

import validator from 'validator';

class FormValidator {
    constructor(rules){
        this.rules = rules;
    }

    setValid(){
        const validation = {};
        this.rules.map(rule => (
            validation[rule.field] = {isValid: true, message: ''}
        ));
        return {isValid: true, ...validation};
    }

    validate(form){
        let validation = this.setValid();
        this.rules.forEach( rule => {
            if (validation[rule.field].isValid){
                const field = form[rule.field].toString();
                const args = rule.args || [];
                const validationMethod = typeof rule.method === 'string' ?
                    validator[rule.method] : rule.method;

                if (validationMethod(field, ...args, form) !== rule.validWhen){
                    validation[rule.field] = {isValid: false, message: rule.message};
                    validation.isValid = false;
                }
            }
        });
        return validation;
    }
}

export default FormValidator;

1 个答案:

答案 0 :(得分:0)

您可以在获取this.state.validation[el.id]键之前检查是否定义了message

就像您不会遇到致命错误一样。

inputObj.map(el => {
  this.state.validation[el.id] && (
    const msg = this.state.validation[el.id].message
  );
})