react-hook 详解及使用
此篇文章主要介绍 react-hook 详解及使用
注意:
React 16.8.0 是第一个支持 Hook 的版本。升级时,请注意更新所有的 package,包括 React DOM。 React Native 从 0.59 版本开始支持 Hook。
Hook 在 class 内部是不起作用的。但你可以使用它们来取代 class 。
1.react-hook 之 什么是 HOOK?
Hook 是 React 16.8 的新增特性。它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性。
Hook 是一个特殊的函数,它可以让你“钩入” React 的特性。
2.react-hook 之 为什么要使用 HOOKS
- Hook 使你在无需修改组件结构的情况下复用状态逻辑
- Hook 将组件中相互关联的部分拆分成更小的函数(比如设置订阅或请求数据)
- Hook 使你在非 class 的情况下可以使用更多的 React 特性
3.Hook 使用规则
Hook 就是 JavaScript 函数,但是使用它们会有两个额外的规则:
- 只能在函数最外层调用 Hook。不要在循环、条件判断或者子函数中调用。
- 只能在 React 的函数组件中调用 Hook。不要在其他 JavaScript 函数中调用。(还有一个地方可以调用 Hook —— 就是自定义的 Hook 中,我们稍后会学习到。)
4.Hook 常见钩子
(1)State Hook
例子:
import React, { useState } from 'react';
function 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>
);
}
等价的 class 示例:
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>
);
}
}
声明 State 变量
在 class 中,我们通过在构造函数中设置 this.state
为 { count: 0 }
来初始化 count
state 为 0
:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
在函数组件中,我们没有 this
,所以我们不能分配或读取 this.state
。我们直接在组件中调用 useState
Hook:
import React, { useState } from 'react';
function Example() {
// 声明一个叫 “count” 的 state 变量
const [count, setCount] = useState(0);
}
useState()
方法里面唯一的参数就是初始 state
读取 State
在 class 中显示当前的 count : <p>You clicked {this.state.count} times</p>
在函数中显示当前的 count : <p>You clicked {count} times</p>
更新 State
在 class 中调用 this.setState()
: <button onClick={() => this.setState({ count: this.state.count + 1 })}> Click me
</button>
在函数中,我们已经有了 setCount
和 count
变量,所以我们不需要 this
: <button onClick={() => setCount(count + 1)}> Click me
</button>