【问题标题】:Prop destructuring inside of react state道具在反应状态内解构
【发布时间】:2018-12-15 18:34:53
【问题描述】:

我为 eslint 添加了 airbnb 配置,它鼓励 prop 和 state 解构,我喜欢它,但是当我在组件中定义 state 时偶然发现了一个问题

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

我收到一个错误

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

我不确定如何正确解构 active 这里的道具? 通常const {active} = this.props 可以工作,但是每当我将它放在状态内或周围时,都会出现意外的语法错误。

【问题讨论】:

  • 你必须将它移动到构造函数中......或者你只是忽略警告
  • @JonasW。明白了,如果我忽略它,它会在任何地方忽略它,或者我最终会得到很多 eslint disable cmets :/ 一个想法是否可以以某种方式全局禁用 state = { pattern?

标签: javascript reactjs eslint


【解决方案1】:

将其保留在类属性中的唯一方法是使用 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 代码块中有一个额外的括号。 ;)
  • ...args 是什么意思(args 前缀的三个点)?
  • @FMaz008 是 rest parameter 或传播参数
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2016-09-06
    • 1970-01-01
    • 2023-03-22
    • 2021-02-22
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    相关资源
    最近更新 更多