最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prop destructuring inside of react state - Stack Overflow

programmeradmin2浏览0评论

I've added airbnb config for eslint that encourages prop and state destructuring, I like it, but stumbled across one problem when I define state in my component

class MyComponent extends Component {
  state = {
    animation: this.props.active ? 1 : 0
  }

I get an error

[eslint] Must use destructuring props assignment (react/destructuring-assignment)

I'm not sure how can I correctly destructure active out of props here? Usually const {active} = this.props works, but whenever I place it inside state or around it I get unexpected syntax error.

I've added airbnb config for eslint that encourages prop and state destructuring, I like it, but stumbled across one problem when I define state in my component

class MyComponent extends Component {
  state = {
    animation: this.props.active ? 1 : 0
  }

I get an error

[eslint] Must use destructuring props assignment (react/destructuring-assignment)

I'm not sure how can I correctly destructure active out of props here? Usually const {active} = this.props works, but whenever I place it inside state or around it I get unexpected syntax error.

Share Improve this question asked Jul 7, 2018 at 10:51 IljaIlja 46.5k103 gold badges289 silver badges526 bronze badges 2
  • 1 you have to move it into the constructor ... or you just ignore the warning – Jonas Wilms Commented Jul 7, 2018 at 10:59
  • @JonasW. gotcha, well if I ignore it it ignores it everywhere or I end up with a lot of eslint disable comments :/ an idea if this can be somehow disabled globally for state = { pattern? – Ilja Commented Jul 7, 2018 at 11:01
Add a comment  | 

2 Answers 2

Reset to default 10

The only to keep it inside of the class property is to use a getter (which will be invoked at the first render):

state = {
  get animation() {
    const { active } = this.props;
    return active ? 1 : 0;
  }
}

Or you use an IIFE to initialize the property:

state = (() => {
  const { active } = this.props;
  return { animation: active ? 1 : 0 };

})()

But thats actually a bit overcomplicating. Another solution would be to move the property into the constructor:

constructor(...args) {
 super(...args);

 const { active } = this.props;
 this.state = { animation: active ? 1 : 0 };

}

But I personally would just ignore that warning here.

You can add this rule to .eslintrc.json

"rules": {
    "react/destructuring-assignment": [
      "error",
      "always",
      {
        "ignoreClassFields": true
      }
    ]
  },
发布评论

评论列表(0)

  1. 暂无评论