一、自定义Hook
自定义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();console.log('stus',stus)// 第一次为[],第二次为真实请求的数据const list = stus.map(it => <li key={it.id}>{it.name}</li>)return <ul>{list}</ul>
}
export default function App() {return (<div><Test /></div>)
}
注意,执行useAllStudent相当于是将
const [students, setStudents] = useState([])useEffect(() => {(async () => {const stus = await getAllStudents();setStudents(stus);})();}, [])return students;
这段代码写在了Test这个组件中,第一次stus为空数组,当通过接口请求到真实数据后,执行了setStudents方法(设置了状态),stus就有值了,所以组件会重新渲染。
使用自定义hook不用考虑那么多,只要调用它就获取到了真实数据,否则会陷入困惑中。
若其他组件也需要学生数据,直接调用即可useAllStudent即可。
若想在类组件中实现这个功能,就需要借助高阶组件了。
import React from 'react'
import useAllStudent from './Hooks/useAllStudents';
function withAllStudents(comp){return class AllStudentsWrapper extends React.Component{state = {stus:[],}async componentDidMount (){const stus = await getAllStudents();this.setState({stus});return <comp {...this.props} stus ={this.state.stus}></comp>}}
}
function Test(props) {const list = props.status.stus.map(it => <li key={it.id}>{it.name}</li>)return <ul>{list}</ul>
}
const TestStudents = withAllStudents(Test);export default function App(){
return (<div><TestStudents/> </div>
)
}
使用高阶组件会麻烦一些,会导致组件的层级嵌套很多,有了hook之后,就是个简单的函数调用。若有其他事情,调用其他自定义hook即可,拆分的就很细了。
之前类组件中在componentDidmount中可能要做很多事情,比如获取数据,设置页面标题,启动定时器。设置一些真实的dom元素,这时使用自定义hook就可以抽离出去,每个hook中都可以实现单一的功能。每个hook中可以有自己的副作用,状态等等。
2.很多组件都需要在第一次加载完成后,启动一个计时器,然后在组件销毁时卸载。
使用Hook的时候,如果没有严格按照Hook的规则进行,eslint的一个插件(eslint-plugin-react-hooks)会报出警告。如何忽略?
/* eslint “react-hooks/exhaustive-deps”: “off” */
Timer.js
//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>// 点击隐藏or显示,隐藏后定时器就会停止,显示后定时器又会出现</div>)
}