我为eslint添加了airbnb配置,它鼓励支持和状态破坏,我喜欢它,但是当我在组件中定义状态时,我偶然发现了一个问题。
class MyComponent extends Component {
state = {
animation: this.props.active ? 1 : 0
}
我犯了个错误
eslint必须使用破坏道具分配(反应/破坏-分配)
我不知道怎么才能正确地将active
从道具中拆下来?通常情况下,const {active} = this.props
可以工作,但是每当我将它放置在状态内或周围时,我都会得到意想不到的语法错误。
发布于 2018-07-07 11:06:33
将其保存在类属性中的唯一方法是使用getter (它将在第一个呈现时被调用):
state = {
get animation() {
const { active } = this.props;
return active ? 1 : 0;
}
}
或者你用一个生命来初始化这个属性:
state = (() => {
const { active } = this.props;
return { animation: active ? 1 : 0 };
})()
但这实际上有点过于复杂了。另一种解决方案是将属性移动到构造函数中:
constructor(...args) {
super(...args);
const { active } = this.props;
this.state = { animation: active ? 1 : 0 };
}
但我个人不理会这里的警告。
发布于 2019-03-14 23:21:01
可以将此规则添加到.eslintrc.json
中。
"rules": {
"react/destructuring-assignment": [
"error",
"always",
{
"ignoreClassFields": true
}
]
},
https://stackoverflow.com/questions/51222448
复制相似问题