简体   繁体   中英

How to fix Eslint error “prefer-destructuring”?

I wanted to shorten an object literal in ES6 like this:

const loc = this.props.local;

The reason is loc.foo(); is a lot easier to type than this.props.local.foo();

But now ESLint complains:

Use object destructuring: prefer-destructuring

I've read the error description on eslint.org but I don't understand it. 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?

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.

It's a new construct in ES 6 that allows you to match property of an object in assignment. 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".

它告诉你使用

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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