![e18967eb596d1450085169001569b202.png](https://i-blog.csdnimg.cn/blog_migrate/e588b9beb9a76652dcc8dcdd25a2c178.jpeg)
一般上来就直接给链接,我鼓励直接看文档:
Using the Effect Hook – Reactreactjs.org![280cd09cec458a8fe12059efdf22bd89.png](https://i-blog.csdnimg.cn/blog_migrate/4e4c6b3870ae6f762e2f49d8bbcb8ab8.png)
![280cd09cec458a8fe12059efdf22bd89.png](https://i-blog.csdnimg.cn/blog_migrate/4e4c6b3870ae6f762e2f49d8bbcb8ab8.png)
Hook使用规则:
1. 只能在 函数 最外层调用Hook, 不要在循环、条件判断、或者子函数中调用
2. 只能在React的函数组件中调用Hook、不要在其他javascript函数中调用
(还有在自定义的Hook中可以调用)
在react Hook中我们已经使用过了state,但是如果全部使用react-hook就会有一个问题?就是class这种声明组件的方式可以使用生命周期,但是在Hook使用中怎样使用其他操作呢?
在react中就是使用Effect来使用生命周期,那Effect指的是哪个生命周期呢?
你可以看做useEffect
Hook 看做componentDidMount
,componentDidUpdate
和componentWillUnmount
这三个函数的组合。
我们在使用怎应该如何使用呢?看下面简单的例子(来源于官网)
import React, { Fragment, useState, useEffect } from 'react'
import { Button } from 'antd'
const HookEffect = () => {
const [count, setCount] = useState(0)
// 相当于componentDidMount 和 componentDidUpdate
// 如果需要使用componentWillUnmount则需要在内部return 一个函数该函数可以实现
useEffect(() => {
document.title = `You clicked ${count} times`
})
return (<Fragment>
<h2>You Clicked {count} times</h2>
<Button onClick={() => setCount(addcount(count))}>点击增加</Button>
</Fragment>)
function addcount (count) {
count += 1
return count
}
}
export default HookEffect
以上代码就是最简单的effect的使用,但是这还不能满足我们的使用
我们需要使用effect进行优化,因为在项目开发中我们需要count这个变量在更新的时候再进行重新渲染,不需要无效的更新
useEffect(() => {
document.title = `You clicked ${count} times`
}, [count])
上面这样的写法就可以避免无效的渲染,(之后我们会写一个例子,表述这个怎样避免)
那以上就基本的effet的使用,现在我们就要说怎样在effect中实现和class声明方式中的componentWillUnmount这个效果
就是在effect这个函数中return 一个函数就可以实现componentWillUnmount这个功能,就像这样
![46193e7371ebd15845d00388ed394fe2.png](https://i-blog.csdnimg.cn/blog_migrate/c6a66a4cd81c47b33d05340e02cb62bc.png)
其实这个例子我们并不能看出来这个这个具体怎么使用,后面我们会写一个小例子综合使用一下useSate和useEffect
focusdroid:ReactHook综合使用小例子(useState、useEffect)zhuanlan.zhihu.com![ff7ea55751f56ee934ab662e07e82e2f.png](https://i-blog.csdnimg.cn/blog_migrate/79b5b814b89cbcbed13e264048288e2a.jpeg)