如何修复 Eslint 错误 "prefer-destructuring"?

How to fix Eslint error "prefer-destructuring"?

我想像这样缩短 ES6 中的对象文字:

const loc = this.props.local;

原因是 loc.foo();this.props.local.foo();

更容易打字

但现在 ESLint 抱怨:

Use object destructuring: prefer-destructuring

我读过 error description on eslint.org 但我不明白。他们有一个看起来与我的代码非常相似的示例,但他们的代码似乎没问题?

var foo = object.bar;

如何在不在 .eslintrc 文件中将其设置为忽略的情况下修复错误?

这是 ES 6 中的一个新结构,允许您在赋值中匹配对象的 属性。您需要的语法是:

const { local: loc } = this.props

转换为:"declare a constant loc and assign it the value of property local from this.props"。

它告诉你使用

const {props: {local: loc}} = this;

更改您的代码:

const local = this.props.local;

至:

const { local } = this.props;

它们是等价的,你可以用同样的方式调用local.foo()。除了第二次使用对象解构。