自定义Hook
一、自定义Hook
State Hook: useState
Effect Hook:useEffect
自定义Hook:将一些常用的、跨越多个组件的Hook功能,抽离出去形成一个函数,该函数就是自定义Hook,自定义Hook,由于其内部需要使用Hook功能,所以它本身也需要按照Hook的规则实现:
- 函数名必须以use开头
- 调用自定义Hook函数时,应该放到顶层
例如:
- 很多组件都需要在第一次加载完成后,获取所有学生数据
//useAllStudents
import { useState, useEffect } from 'react'
import { getAllStudents } from "../components/services/student"
/**
* 当组件首次加载完成后,获取所有学生数据
*/
export default function useAllStudents() {
const [students, setStudents] = useState([])
useEffect(() => {
(async () => {
const stus = await getAllStudents();
setStudents(stus);
})();
}, [])
return students;
}
import React from 'react'
import useAllStudent from './Hooks/useAllStudents';
function Test() {
const stus = useAllStudent();
const list = stus.map(it => <li key={it.id}>{it.name}</li>)
return <ul>{list}</ul>
}
export default function App() {
return (
<div>
<Test />
</div>
)
}
- 很多组件都需要在第一次加载完成后,启动一个计时器,然后在组件销毁时卸载
使用Hook的时候,如果没有严格按照Hook的规则进行,eslint的一个插件(eslint-plugin-react-hooks)会报出警告
//Timer
/* eslint "react-hooks/exhaustive-deps": "off" */
import { useEffect } from "react"
/**
* 组件首次渲染后,启动一个Interval计时器
* 组件卸载后,清除该计时器
*/
export default (func, duration) => {
useEffect(() => {
const timer = setInterval(func, duration)
return () => {
clearInterval(timer);
}
}, [])
}
import React,{useState} from 'react'
import useTimer from "./Hooks/useTimer"
function Test(props) {
useTimer(()=>{
console.log('Test组件')
},1000);
return <h1>Test组件</h1>
}
export default function App() {
const [visible, setVisible] = useState(true)
return (
<div>
{
visible && <Test/>
}
<button onClick={()=>{
setVisible(!visible);
}}>点击</button>
</div>
)
}
博主开始运营自己的公众号啦,感兴趣的可以关注“飞羽逐星”微信公众号哦,拿起手机就能阅读感兴趣的博客啦!