【问题标题】:"Must use destructuring state assignment": How to destructure from object and place on property inside object literal“必须使用解构状态分配”:如何从对象解构并放置在对象文字内的属性上
【发布时间】:2019-12-23 06:24:26
【问题描述】:

在 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),
}

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

【问题讨论】:

  • 我在某处看到了支持{ this.state.thing, ... }的提案,但是我找不到了,所以似乎不会指定。

标签: javascript reactjs ecmascript-6


【解决方案1】:

是的,你可以通过箭头功能做到这一点

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

【讨论】:

  • 这个答案确实帮助我更多地掌握函数式编程。猜测有人对此投了反对票,因为它没有以直接回答问题的方式格式化,但thing: (obj => obj.thing)(this.state) 有效。
  • 如果有人反对也没关系,这个问题不是那么重要...我也喜欢并尊重FP,所以我喜欢这样的事情
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2021-09-09
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 2020-06-11
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多