Introducing Hooks

Hooks let you use state and other React features without writing a class.
使用Hooks的原因:
  • 复杂组件变得难以理解
    • componentDidMountcomponentDidUpdatecomponentWillUnmount
  • Classes使得机器和人都难以理解

Hooks at a Glance

📌 State Hook

useState是一个Hook,我们借助它为函数组件添加了一些local state,React会在各个re-renders之间持久化state。useState返回一个pair:当前的state值和更新state的函数。参数为state的初始值。
与类中的this.setState的区别:不会将旧的state与新的state合并。

⚡️ Effect Hook

side effects:会影响其他组件并且不能在rendering期间处理的操作。例如data fetching, subscriptions, or manually changing the DOM from React components。
useEffect为函数组件添加处理side effects的能力,它将类的生命周期函数componentDidMount, componentDidUpdate, and componentWillUnmount合并为一个,在每次render函数执行之后都会调用传入的effect。
useEffect可以接收两个参数,第一个参数为一个函数用于处理effect,如果该函数返回一个清理函数,则React会在执行下一次render之前调用该函数;第二个参数为可选的数组,用于控制是否需要调用effect。
如果第二个参数传递空数组[],则表示effect不依赖于props和state中的任何值,所以只会在componentDidMountcomponentWillUnmount的时候调用effect。

Building Your Own Hooks

自定义HOOK是一个以"use"开头的JavaScript函数,可以调用其他的Hooks。
 
badge