使用hook的好处:
1.可以不再使用class(有状态组件)
2.不用考虑复杂的react生命周期钩子函数
3.让this的处理变得简单
例子
普通版本:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {
this.state.count} times</p>
<button onClick={
() => this.setState({
count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
使用hooks的版本:
import {
useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {
count} times</p>
<button onClick={
(