别名 ES6 解构

dbr*_*rrt 1 javascript ecmascript-6 reactjs

我正在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?
}
Run Code Online (Sandbox Code Playgroud)

Ori*_*ori 6

要获取字段名称,您需要对计算属性名称使用解构,并将结果分配给变量:

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

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

  console.log(value);
}

checkField('abc');
Run Code Online (Sandbox Code Playgroud)

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

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

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

  console.log(nameOfField);
}

checkField('abc');
Run Code Online (Sandbox Code Playgroud)