我们看一下一个简单的有状态组件是什么样子的:
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={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
可以看到,Example
变成了一个函数,但这个函数却有自己的状态,同时它还可以更新自己的状态,这个函数之所以这么好用,是因为它注入了一个hook--useState
,就是这个hook让我们的函数变成了一个有状态的函数。