本例子实现了自定义hook之首页数据请求动作封装 hooks,具体代码如下
export type OrganData = {dis: Array<{ disease: string; id: number }>;is_delete: number;name: string;organ_id: number;parent_id: number;sort: number;
};
export type SwiperData = {id: string;module1_id: string;module2_id: string;title: string;sort: string;has_app_header: string;url: string;content: string;litpic: string;posttime: string;status: string;weapp_url: string;
};
export interface ResponseType<T> {code: number;msg: string;data?: T;runtime?: number;
}
import { useEffect, useState } from 'react';
import { useToast } from 'taro-hooks';
import Apis from '../services';export enum FetchType {Swiper, // 首页swiper 数据Nav, // 首页nav 数据
}/*** 首页数据请求动作封装 hooks* @param type 请求类型* @returns*/
const useFetchData = (type: FetchType) => {const [data, setData] = useState([]);const [showToast] = useToast();useEffect(() => {const fetchData = async () => {let res;if (type === FetchType.Swiper) {res = (await Apis.fetchSwiperData()) as ResponseType<SwiperData[]>;}if (type === FetchType.Nav) {res = (await Apis.fetchOrganData()) as ResponseType<OrganData[]>;}if (res?.code === 200) {setData(res?.data);} else {showToast({ title: res?.msg });}};fetchData();}, [showToast, type]);return [data];
};export default useFetchData;