本例子實現了自定義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;