React状态中的属性解构

13

我已经为ESLint添加了Airbnb配置,以鼓励使用属性和状态解构。我很喜欢它,但是当我在组件中定义状态时遇到了一个问题。

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

我遇到了一个错误

[eslint] 必须使用解构的方式对 props 进行赋值 (react/destructuring-assignment)

我不确定如何在这里正确地对 props 解构出 active? 通常情况下 const {active} = this.props 可以使用,但是每当我将其放在 state 内部或周围时,我会遇到意外的语法错误。


1
你必须将它移动到构造函数中...或者你可以忽略这个警告。 - Jonas Wilms
@JonasW. 好的,如果我忽略它,它会在任何地方都被忽略,或者我最终会有很多 eslint 禁用注释 :/ 你有什么想法,是否可以在全局范围内禁用 state = { pattern? - Ilja
2个回答

10

唯一将其保留在类属性内的方法是使用getter(将在第一次渲染时调用):

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

或者您可以使用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 };

}

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


IIFE 代码块中有一个额外的括号。 ;) - Ignatius
"...args" 是什么意思(在 args 前面有三个点)? - FMaz008
1
@FMaz008 那是一个 剩余参数 或者扩展运算符。 - Jonas Wilms

5

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接