javascript - 不能使用 this.state,因为我使用 eslint,“必须使用解构状态分配”/destructuring-assignment 反应
问题描述
我遇到了一些错误,因为我使用了一些 this.setState 语句,因此我无法调用我的语句。
我在这里遇到错误this.state.show
handleClick() {
this.setState({ show: !this.state.show }); <<<------EROR HERE
}
这是我的完整代码
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>
);
}
}
导出默认你好;
解决方案
eslint 规则destructuring-assignment
是强制执行此操作的。
但是你有比这更大的问题,因为你不应该this.state
在 a 期间阅读setState()
,如果你想确保你会得到正确的值(因为React 组件状态可能是异步设置的。)
而是传递一个函数,将(当前)状态作为其参数:
handleClick() {
this.setState(state => {
return {show: !state.show } // not this.state.show
});
}
推荐阅读
- java - 不使用 FXML 时如何修复 Java 错误?
- javascript - 如何缩小 Laravel .js 和 .css 文件
- github - Azure Pipelines 拒绝创建 GitHub 版本
- python - 如何在 django 中提供动态文件?
- python - 如何在 matplotlib 的绘图曲线中设置黑暗?
- r - 在 R 中处理零的同时对数转换(受其他约束)
- go - 通过局域网接收文件时将文件保存到网络文件夹时出现问题 - Golang
- python - 为什么我不能只更改一个 pandas 列中的值?
- ios - 如何从 SwiftUI 列表和领域中删除数据
- javascript - react-router-dom 中缺少交换机和路由器模块