Javascript 如何修复 Eslint 错误“prefer-destructuring”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47395070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fix Eslint error "prefer-destructuring"?
提问by Timo
I wanted to shorten an object literal in ES6 like this:
我想像这样缩短 ES6 中的对象字面量:
const loc = this.props.local;
The reason is loc.foo();is a lot easier to type than this.props.local.foo();
原因是loc.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.orgbut I don't understand it. They have an example which looks very similar to my code but theirs seem to be ok?
我已经阅读了eslint.org 上的错误描述,但我不明白。他们有一个看起来与我的代码非常相似的示例,但他们的示例似乎没问题?
var foo = object.bar;
How can I fix the error without setting it to ignore in the .eslintrcfile?
如何修复错误而不将其设置为在.eslintrc文件中忽略?
回答by Badis Merabet
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. except that the second use object destructuring.
它们是等效的,您可以local.foo()以相同的方式调用。除了第二次使用对象解构。
回答by ilmirons
It's a new construct in ES 6 that allows you to match property of an object in assignment. The syntax you need is:
它是 ES 6 中的一个新构造,允许您在赋值中匹配对象的属性。您需要的语法是:
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 为其分配本地属性的值”。
回答by Bergi
It's telling you to use
它告诉你使用
const {props: {local: loc}} = this;

