广东深圳旅游必去十大景点如何优化网络
现在越来越多的项目开始ts化,我们今天就一块学习一下,关于ts的请求封装。
首先要安装两个依赖:
npm i axios -S
npm i ahooks -S
引入:
import { useRequest } from 'ahooks';
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
定义一个泛型接口,用于指定请求参数和响应数据的类型
interface RequestParams<T> {url: string;method: string;data?: T;
}// 定义一个范型函数,用于发送 GET 请求
function get<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {return axios.get<T>(url, config);
}// 定义一个范型函数,用于发送 POST 请求
function post<T>(params: RequestParams<T>, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {return axios.post<T>(params.url, params.data, config);
}
使用ahooks的useRequest:
// 使用 useRequest hooks 发送 GET 请求const { data, loading, error } = useRequest<{ name: string }>('https://api.example.com/data', {requestMethod: () => get('https://api.example.com/data'),});
直接使用get、post:
// 调用 GET 方法
get<{ name: string }>('https://api.example.com/data').then(response => {console.log(response.data.name);}).catch(error => {console.error(error);});// 调用 POST 方法
const postData = { name: 'John' };
const postParams = { url: 'https://api.example.com/data', method: 'post', data: postData };
post<{ status: string }>(postParams).then(response => {console.log(response.data.status);}).catch(error => {console.error(error);});