自定义Hook的作用
自定义 Hook,就是使用了内置 Hook 的普通函数。
我们可以把函数组件中重复处理的逻辑抽离出来封装成hook,减少代码量,方便快速编写函数组件。
自定义Hook的标准
- 要以
use
开头的小驼峰命名。如useRequest
、useLoad
、useExport
等等。
自定义Hook的例子
useRequest
基于axios
请求异步API数据的自定义hook
import { AxiosResponse } from "axios";
import { useState, useEffect } from "react";
interface Responses<D> {
code: number,
message: string,
data: D,
};
type UseRequest<D> = [
data: D,
setData: React.Dispatch<React.SetStateAction<D>>,
handleUpdate: () => void,
]
export default function useRequest<D = any, P = any>(
requestApi: (params?: P) => Promise<AxiosResponse<Responses<D>>>,
params?: P,
handleError?: (err?: any | Responses<D>) => void,
handleFinally?: () => void,
): UseRequest<D> {
const [data, setData] = useState<D>();
const [update, setUpdate] = useState(1);
const handleUpdate = () => {
setUpdate((value) => {
return value + 1;
});
};
useEffect(() => {
let active = true;
if (active) {
requestApi(params).then((response) => {
switch (response.data.code) {
case 0: {
setData(response.data.data);
} break;
default: {
// You error handle...
handleError && handleError(response.data);
};
}
}).catch(handleError).finally(handleFinally);
}
return () => {
active = false;
};
}, [update]);
return [data, setData, handleUpdate];
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。