繁体   English   中英

“必须使用解构状态赋值”:如何从对象中解构并放置在对象字面量内的属性上

[英]"Must use destructuring state assignment": How to destructure from object and place on property inside object literal

在 React 项目中,我想通过在特定时间记录状态的特定部分来快速解决问题。

console.error('this.state.thing', this.state.thing);

这样做,我的 ESLint 配置给了我错误“必须使用解构状态分配”。 所以,我要么关闭这个 ESLint 规则,要么我必须这样做:

const { thing } = this.state;
console.error('this.state.thing', thing);

这很好,但它让我想知道我是否可以一次性在对象文字中以相同的方式解构一个属性:

const objectLiteral = {
  thing: this.state.thing, // how to destructure thing out of state?
  stuff1,
  stuff2: otherData,
};

const somethingLikeThis = {
  thing: ({ thing } = this.state),
}

只是好奇是否有办法做到这一点。

不在文字内部,但您可以将值分解为对象属性:

({thing: objectLiteral.thing} = this.state);

是的,你可以通过箭头函数来完成

console.error('this.state.thing', (obj => obj.thing)(this.state))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM