Hook是什么
- Hook是React16.8的新增特性,提供内置钩子函数(也可自定义),它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性
- 在以函数声名的组件中使用,不可以在class声名的组件中使用
如何使用Hook(以使用state为例)
引用
1
import React, { useState } from 'react';
定义及使用
使用useState会返回两个对象
- 经过初始化的state
- 改变state的方法
1
2
3
4
5
6
7
8
9
10
11
12
13function Example() {
// 声明一个新的叫做 “count” 的 state 变量
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Hook有哪些优势呢?
避免编写重复代码
1
2
3
4
5
6
7componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}1
2
3useEffect(() => {
document.title = `You clicked ${count} times`;
});将紧密性强的代码放到一起执行,逻辑就会更好理解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19componentDidMount() {
ChatAPI.subscribeToFriendStatus(
this.props.friend.id,
this.handleStatusChange
);
}
componentWillUnmount() {
ChatAPI.unsubscribeFromFriendStatus(
this.props.friend.id,
this.handleStatusChange
);
}
handleStatusChange(status) {
this.setState({
isOnline: status.isOnline
});
}1
2
3
4
5
6
7
8
9
10
11useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});useEffect返回的函数会在组件卸载时执行