简体   繁体   中英

Destructuring state assignment with logical operators

On this.state.keyboard ESLint gives me the error "Must use destructuring state assignment (react/destructuring-assignment)".

const keyboard = this.state.keyboard || data[0];

Of course, I can do something like:

let {keyboard} = this.state;
keyboard = keyboard || data[0]; 

But is there a way to do it in one line and using const ? Thank you.

I don't think there is a way to do it in one line with const and get the exact same behaviour as you have, ie, to assign data[0] to keyboard if it is falsy.

If you destructure keyboard and give it a default value like this:

const { keyboard = data[0] } = this.state;

keyboard will be set to data[0] only if it is defined in this.state . And the same happens with this statement:

const { keyboard } = { keyboard: data[0], ...this.state };

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