[英]can't using this.state because i use eslint, “Must use destructuring state assignment” /destructuring-assignment react
i got some error because i using some this.setState statement, because of that i can't call my statement.我遇到了一些错误,因为我使用了一些 this.setState 语句,因此我无法调用我的语句。
i got error here on this.state.show
我在
this.state.show
上遇到错误
handleClick() {
this.setState({ show: !this.state.show }); <<<------EROR HERE
}
and this my full code这是我的完整代码
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = { show: false };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({ show: !this.state.show });
}
render() {
return (
<HeroStyles>
<Zoom>
<div className="container">
<div className="Kotak">
<h1 className="heading">
<span> this is hello </span>
<h2>
stay{' '}
<span>
<Typewriter
loop={0}
cursor
cursorStyle="_"
delaySpeed={3000}
words={['Positive', 'Negative']}
/>
</span>{' '}
<span>
<Typewriter
loop={1}
cursor
cursorStyle="_"
delaySpeed={3000}
words={['Kawan']}
/>
</span>
</h2>
</h1>
<Zoom delay={500}>
<div className="foto">
waymo
<div className="lingkaran" />
<img src={foto} alt="" onClick={this.handleClick} />
Guna Dharma
</div>
</Zoom>
<Zoom opposite when={this.state.show}>
<h1>React Reveal</h1>
</Zoom>
</div>
</div>
</Zoom>
</HeroStyles>
);
}
}
export default Hello;导出默认你好;
You have the destructuring-assignment rule in place.您已经制定了解构分配规则。
Enforce consistent usage of destructuring assignment of props, state, and context (react/destructuring-assignment)
强制使用 props、state 和 context 的解构赋值(react/destructuring-assignment)
You have to destructure what you want from the state first:你必须首先从状态中解构你想要的东西:
handleClick() {
const { show } = this.state;
this.setState({ show: !show });
}
If you don't want to do this, you can disable the rule from ESLint.如果你不想这样做,你可以从 ESLint 禁用规则。
The eslint rule destructuring-assignment
is what enforces this. eslint 规则
destructuring-assignment
是强制执行此操作的原因。
But you have bigger problems than that, because you should not read this.state
during a setState()
, if you want to be sure you'll get the correct values (because React component state may be set asynchronously .)但是你有比这更大的问题,因为你不应该在
setState()
期间读取this.state
,如果你想确保你会得到正确的值(因为React 组件状态可能是异步设置的。)
Pass a function instead, with the (current) state as its parameter:传递一个函数,以(当前)状态作为其参数:
handleClick() {
this.setState(state => {
return {show: !state.show } // not this.state.show
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.