原生xhr 封装 axios实现, 以及如何使TS添加类型注解, 主要使用了泛型参数,加深你对泛型参数的理解
export type configType<T = unknown> = {
url: string
method?: XMLHttpRequest['method']
dataType?: XMLHttpRequestResponseType
data?: Record<string, unknown>
params?: Record<string, string>
success?: (res: T) => void
fail?: (err: unknown) => void
complete?: () => void
}
export interface resultType<T> {
code: number
data: T,
error: null
updateTime: number
}
import type { configType } from '../type/myAxios'
export function myAxios<T>(config: configType<T>) {
new Promise<T>((reslove, reject) => {
const xhr = new XMLHttpRequest()
if (config.params) {
const params = new URLSearchParams(config.params)
const queryString = params.toString()
config.url += `?${queryString}`
}
xhr.open(config.method || 'GET', config.url)
xhr.responseType = config.dataType || 'json'
xhr.addEventListener('loadend', () => {
if (xhr.status >= 200 && xhr.status < 300) {
reslove(xhr.response as T)
} else {
return reject(xhr.response)
}
})
if (config.data) {
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(JSON.stringify(config.data))
} else {
xhr.send()
}
}).then(res => {
config.success?.(res)
}).catch(err => {
config.fail?.(err)
}).finally(() => {
config.complete?.()
})
}
```App.tsx
import { resultType, dataType } from './type/myAxios'
import { useEffect } from 'react'
import { myAxios } from './utils/myAxios'
function App() {
useEffect(() => {
// 获取随机名言
myAxios<resultType<dataType>>({
url: 'https://api.xygeng.cn/one',
success(res) {
console.log(res)
},
dataType: 'json'
})
}, [])
return <>this is app</>
}
export default App