1. 什么是hooks
A way to use state and other React features without writing a class.
React Hooks是React从v16.8引入的一种新的更简单更方便的编写组件的功能。hooks提供了一种可以不用写class而直接使用state和其他React特性的能力,而且自定义hooks可以将公共逻辑抽离,使之可以在多个组件之间共享。
2. hooks的由来
hooks
主要是为了解决以下3个React问题
组件带状态变得难以复用
复杂逻辑不用跟随生命周期
-
解决难以理解的class
js中的this取值跟其他面向对象语言都不同,是在运行时决定的。为了解决这一痛点,才有了箭头函数的this绑定特性。另外何时使用class component 和 function component也是一件容易纠结的事,对于优化方面来说,class component在预编译和压缩方面也比普通函数困难得多,还容易出错。
3. 使用
-
state hook
import { useState } from 'react' function Demo() { const [count, setCount] = useState(0) return ( <div> <p>count: { count }</p> <button onClick={() => { setCount(count + 1) }}>点击</button> </div> ) }
useState
只有一个参数,即count的初始值,可以是任意类型。如果count是对象,useState
不会像setState
自动合并原state
,可以:setState(preV => { return { ...preV, ...updateV } // Object.assign(preV, updateV) })
多个
state
变量只需要多次调用useState
即可... function Demo2() { const [count, setCount] = useState(0) const [fruit, setFruit] = useState('apple') ... }
-
Effect hook
我们希望组件在DOM挂载和更新后执行相同的操作,使用React Effect hooks写法:
import React, { useEffect } from 'react' function Demo3() { const [count, setCount] = useState(0) useEffect(() => { document.title = `clicked ${count} times` }) }
传统class component写法:
import React from 'react' class Demo3 extends React.Component{ constrctor(props) { super(props) this.state = { count: 0 } } componentDidMount () { document.title = `clicked ${this.state.count} times` } compoenntDidUpdate () { document.title = `clicked ${this.state.count} times` } ... }
传统class component,我们需要在两个生命周期中调用相同的函数,使用Effect特性React会保存传递的函数,并在DOM渲染后调用该函数。
useEffect
同时拥有componentDidMount
,componentDidUpdate
,componentWillUnmount
三个生命周期的执行时机。但Effct并不会阻塞浏览的渲染,使应用看起来更加流畅。有时候我们为了防止内存泄漏需要清除的Effct,class component中需要在
componentDIdMount
中注册并在componentWillUnmount
中销毁,使用hooks只需要在useEffct
中返回一个函数即可function Demo4() { useEffct(() => { let timer = setInterval(() => { console.log(1) }) return () => { clearInterval(timer) } }) }
当
useEffct
返回一个函数的时候,React会在下一次执行副作用之前调用一次清理函数。组件挂载 —> 执行副作用 —>组件更新 —>执行清理函数—>执行副作用—>组件更新—>执行清理函数—>组件卸载
所以每次
state
更新我们都会重新渲染一次,如果state
值没有改变的情况下(原来count是5改变后还是5),我们不想调用Effct,只需要在useEffct
函数中传入第二个参数[count]
即可。React会对前一次渲染的[5]和后一次渲染的[5]对比,数组内元素全部相等,React就会跳过这个Effct,同时实现了性能的优化。该参数为数组,可以传多个数组,一般会将Effct用到的props
和state
都传进去。清除函数同理。如果
useEffct
传入的第二个参数是一个[]
,等效于componentDidMount
和componentWillUnmount
4. hooks规则
只能在
React 函数式组件
中调用Hook只能在
函数
最外层调用Hook只能用在
函数
最顶层不能用在循环、条件判断语句,嵌套函数
ESLint插件
eslint-plugin-react-hooks
格式规范
...