Javascript 在react状态内部进行Prop分解

Javascript 在react状态内部进行Prop分解,javascript,reactjs,eslint,Javascript,Reactjs,Eslint,我已经为eslint添加了airbnb config,它鼓励道具和状态分解,我很喜欢,但在我的组件中定义状态时遇到了一个问题 class MyComponent extends Component { state = { animation: this.props.active ? 1 : 0 } 我犯了一个错误 [eslint]必须使用解构道具分配 (反应/分解分配) 我不知道如何正确地将活动的从道具中解构出来? 通常const{active}=this.props可以工作,

我已经为eslint添加了airbnb config,它鼓励道具和状态分解,我很喜欢,但在我的组件中定义状态时遇到了一个问题

class MyComponent extends Component {
  state = {
    animation: this.props.active ? 1 : 0
  }
我犯了一个错误

[eslint]必须使用解构道具分配 (反应/分解分配)

我不知道如何正确地将
活动的
从道具中解构出来?

通常
const{active}=this.props
可以工作,但每当我将它放在state内部或周围时,就会出现意外的语法错误。

将它放在class属性内部的唯一方法是使用getter(将在第一次呈现时调用):

或者使用IIFE初始化属性:

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

})()
但这实际上有点过于复杂了。另一种解决方案是将属性移动到构造函数中:

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

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

}

但是我个人会忽略这里的警告。

您可以将此规则添加到
.eslintrc.json

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

您必须将其移动到构造函数中。。。或者你只是忽略了warning@JonasW. 明白了,如果我忽略它,它会到处忽略它,或者我会得到很多eslint disable注释:/这是一个想法,如果这可以被全局禁用,用于state={pattern?IIFE代码块中有一个额外的括号。;)args是什么意思(三点前缀args)?@FMaz008这是一个或一个扩展参数
"rules": {
    "react/destructuring-assignment": [
      "error",
      "always",
      {
        "ignoreClassFields": true
      }
    ]
  },