反应状态内部的道具破坏 [英] Prop destructuring inside of react state
问题描述
我喜欢为eslint添加airbnb配置,以鼓励道具和状态的分解,但是我在组件中定义状态时偶然发现了一个问题
I've added airbnb config for eslint that encourages prop and state destructuring, I like it, but stumbled across one problem when I define state in my component
class MyComponent extends Component {
state = {
animation: this.props.active ? 1 : 0
}
我得到一个错误
[eslint]必须使用破坏性道具分配(反应/破坏性分配)
[eslint] Must use destructuring props assignment (react/destructuring-assignment)
我不确定如何从这里的道具中正确地破坏 active
?通常 const {active} = this.props
可以工作,但是每当我将其放置在状态内或状态周围时,都会出现意外的语法错误.
I'm not sure how can I correctly destructure active
out of props here?
Usually const {active} = this.props
works, but whenever I place it inside state or around it I get unexpected syntax error.
推荐答案
将其保留在class属性中的唯一方法是使用getter(将在第一个渲染器上调用):
The only to keep it inside of the class property is to use a getter (which will be invoked at the first render):
state = {
get animation() {
const { active } = this.props;
return active ? 1 : 0;
}
}
或者您使用IIFE初始化属性:
Or you use an IIFE to initialize the property:
state = (() => {
const { active } = this.props;
return { animation: active ? 1 : 0 };
})()
但是那实际上有点太复杂了.另一个解决方案是将属性移到构造函数中:
But thats actually a bit overcomplicating. Another solution would be to move the property into the constructor:
constructor(...args) {
super(...args);
const { active } = this.props;
this.state = { animation: active ? 1 : 0 };
}
但我个人只是在这里忽略该警告.
But I personally would just ignore that warning here.
这篇关于反应状态内部的道具破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!