Prop destructuring inside of react state

大兔子大兔子 提交于 2021-01-26 19:49:15

问题


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.


回答1:


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.




回答2:


You can add this rule to .eslintrc.json

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


来源:https://stackoverflow.com/questions/51222448/prop-destructuring-inside-of-react-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!