React Hook 初体验
1.Hook 简介
Hook 是一些可以让你在函数组件里“钩入” React state 及生命周期等特性的函数。Hook 不能在 class 组件中使用 —— 这使得你不使用 class 也能使用 React。
2.动机
官方解释:
- 组件之间复用状态逻辑很难
- 复杂组件变得难以理解
- 难以理解的 class
3.Hook 规则
只在最顶层使用 Hook
不要在循环,条件或嵌套函数中调用 Hook, 确保总是在你的 React 函数的最顶层调用他们。
只在 React 函数中调用 Hook
不要在普通的 JavaScript 函数中调用 Hook。你可以:
- ✅ 在 React 的函数组件中调用 Hook
- ✅ 在自定义 Hook 中调用其他 Hook
4.基础 Hook
useState
function 组件示例:
|  | function Example() {
 const [count, setCount] = useState(0)
 return (
 <div>
 <p>You clicked {count} times</p>
 <button onClick={() => setCount(count + 1)}>Click me</button>
 </div>
 )
 }
 
 | 
等价的 Class 示例:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | 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>
 )
 }
 }
 
 | 
useEffect
Effect Hook 可以让你在函数组件中执行副作用操作
|  | import React, { useState, useEffect } from 'react'function Example() {
 const [count, setCount] = useState(0)
 
 
 useEffect(() => {
 
 document.title = `You clicked ${count} times`
 })
 return (
 <div>
 <p>You clicked {count} times</p>
 <button onClick={() => setCount(count + 1)}>Click me</button>
 </div>
 )
 }
 
 | 
提示
如果你熟悉 React class 的生命周期函数,你可以把 useEffect Hook 看做 componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合。
无需清除的 effect
使用 class 的示例:
|  | componentDidMount() {
 document.title = `You clicked ${this.state.count} times`;
 }
 componentDidUpdate() {
 document.title = `You clicked ${this.state.count} times`;
 }
 
 | 
当你使用 hook:
|  | useEffect(() => {
 document.title = `You clicked ${count} times`
 })
 
 | 
需要清除的 effect
使用 class 的示例:
|  | componentDidMount() {
 ChatAPI.subscribeToFriendStatus(
 this.props.friend.id,
 );
 }
 componentWillUnmount() {
 ChatAPI.unsubscribeFromFriendStatus(
 this.props.friend.id,
 );
 }
 
 | 
当你使用 hook:
|  | useEffect(() => {
 ChatAPI.subscribeToFriendStatus(props.friend.id)
 
 return () => {
 ChatAPI.unsubscribeFromFriendStatus(props.friend.id)
 }
 })
 
 | 
5.额外的 Hook
6.自定义 Hook