别名ES6解构

时间:2017-09-10 20:53:09

标签: javascript reactjs ecmascript-6

我正在为我的表单创建一个泛型函数checkField,我希望能够从状态(或任何JavaScript对象)中提取我作为参数传递的变量

checkField(fieldname) {
   const {
     validityFieldObj,
     fieldname
   } = this.state

   // Would be equivalent to `this.state[fieldname]`
   // But I can't get fieldname from this.state destructuration,
   // as it as already been delcared in the parameter.
   // Any alternative to this issue?
}

1 个答案:

答案 0 :(得分:3)

要获取字段名称,您需要使用destructuring with computed property name,并将结果分配给变量:

const state = {
  validityFieldObj: {},
  abc: 3
};

function checkField(fieldname) {
   const {
     validityFieldObj,
     [fieldname]: value
   } = state;

  console.log(value);
}

checkField('abc');

如果您需要提取属性名称fieldName,则可以使用别名:

const state = {
  validityFieldObj: {},
  fieldname: 'abc'
};

function checkField(fieldname) {
  const {
    validityFieldObj,
    fieldname: nameOfField
  } = state;

  console.log(nameOfField);
}

checkField('abc');