自定义hook
- 将常用的、跨域多个组件的Hook功能,抽离出去形成一个函数,该函数就是自定义Hook,由于其内部需要使用Hook功能,所以它本身也需要按照hook的规则实现
- 函数名必须以use开头
- 调用自定义hook函数时,应该放在组件顶层
例子请求数据的函数
import React, { useState, useEffect } from 'react'
// => 通过类型获取不同的wife列表数据
function useGetWifes(type, page=1, limit = 10) {
const [wifes, setWifes] = useState([])
useEffect(() => {
(async () => {
const wifeList = await getWifes(type)
setWifes(wifeList)
})();
return wifes
}, [type, page, limit])
}
export function App() {
const wifes = useGetWifes('御姐')
return (
<div>
{wifes}
</div>
)
}
- 类组件高阶组件对比
- 整个层级变得复杂了
- 逻辑变得复杂了
function withAllWifes(Comp) {
return class AllWifesComp extends React.Component {
state = {
w: []
}
async componentDidMount () {
const w = await getWifes()
this.setState({w})
}
return (
<Comp {...this.props} w={this.state.w}/>
)
}
}
首次渲染时调用一次定时器,销毁时调用一次清理 的Hook
/* eslint "react-hook/exhaustive-deps": "off" */
import { useEffect } from 'react'
export default (func, duration) => {
useEffect(() => {
const timer = setInterval(func, duration)
return () => {
clearInterval(timer)
}
},[])
}
使用hook的时候,如果没有严格按照Hook的规则进行,但是特殊情况下,我们知道自己干嘛,不想代码检测
- eslint-plugin-react-hook插件会报警告
- 文件顶部 /* eslint "react-hook/exhaustive-deps": "off" */