我喜欢为eslint添加airbnb配置,以鼓励进行prop和state的分解,但是我在组件中定义状态时偶然发现了一个问题
class MyComponent extends Component {
state = {
animation: this.props.active ? 1 : 0
}
我遇到错误
[eslint]必须使用破坏道具分配 (反应/破坏性分配)
我不确定如何从这里的道具中正确解构active
?
通常const {active} = this.props
可以正常工作,但是每当我将它放在状态内或状态周围时,都会出现意外的语法错误。
答案 0 :(得分:10)
将其保留在class属性中的唯一方法是使用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 };
}
但我个人只是在这里忽略该警告。
答案 1 :(得分:1)
您可以将此规则添加到.eslintrc.json
"rules": {
"react/destructuring-assignment": [
"error",
"always",
{
"ignoreClassFields": true
}
]
},