简体   繁体   English

如何修复 Eslint 错误“prefer-destructuring”?

[英]How to fix Eslint error “prefer-destructuring”?

I wanted to shorten an object literal in ES6 like this:我想像这样缩短 ES6 中的对象字面量:

const loc = this.props.local;

The reason is loc.foo();原因是loc.foo(); is a lot easier to type than this.props.local.foo();this.props.local.foo();更容易输入this.props.local.foo();

But now ESLint complains:但现在 ESLint 抱怨:

Use object destructuring: prefer-destructuring使用对象解构:prefer-destructuring

I've read the error description on eslint.org but I don't understand it.我已经阅读了eslint.org 上错误描述,但我不明白。 They have an example which looks very similar to my code but theirs seem to be ok?他们有一个看起来与我的代码非常相似的示例,但他们的示例似乎没问题?

var foo = object.bar;

How can I fix the error without setting it to ignore in the .eslintrc file?如何修复错误而不将其设置为在.eslintrc文件中忽略?

change your code from:更改您的代码:

const local = this.props.local;

to:到:

const { local } = this.props;

They are equivalent and you can call local.foo() in the same way.它们是等效的,您可以以相同的方式调用local.foo() except that the second use object destructuring.除了第二次使用对象解构。

It's a new construct in ES 6 that allows you to match property of an object in assignment.它是 ES 6 中的一个新构造,允许您在赋值中匹配对象的属性。 The syntax you need is:您需要的语法是:

const { local: loc } = this.props

which translates to: "declare a constant loc and assign it the value of property local from this.props".转换为:“声明一个常量 loc 并从 this.props 为其分配本地属性的值”。

它告诉你使用

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

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

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