javascript - react 状态内部的 Prop 解构

标签 javascript reactjs eslint

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

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

我得到一个错误

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

我不确定如何正确地从 props 中解构 active ? 通常 const {active} = this.props 有效,但每当我将它放在 state 内部或周围时,我都会遇到意外的语法错误。

最佳答案

唯一将它保留在类属性内的方法是使用 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 };

}

但我个人会忽略此处的警告。

关于javascript - react 状态内部的 Prop 解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51222448/

相关文章:

javascript - 我想使用用户脚本捕获tinymce编辑器中的键盘事件(即添加键盘快捷键)

javascript - React 中 HTML 输入类型数值四舍五入到小数点后两位

reactjs - 如何在 React 应用程序中使用 openai 的 apikey 创建一个 .env?

javascript - 加载规则时出错 '@typescript-eslint/dot-notation'

javascript - eslint 规则强制 ) 和 { 之间留有空格

javascript - ajax 加载的 html 中的多个 jQuery 插件实例

javascript - 重置单选按钮在 AngularJS 中不起作用

node.js - 忽略整个项目中 eslint 的特定错误

javascript - 多个标记与div背景通信失败

javascript - Redux:帮助过滤/删除我的 reducer 中属性的数组项