能否请教下与@umi/hooks的结合
TIS-OMiddle opened this issue · 1 comments
TIS-OMiddle commented
😢原谅我的ts水平。。目前想利用makeRequestHook,把请求函数封装进去umi的useRequest(为了直观去掉一些类型):
export default function makeRequestHook(request) {
return function(requestData: TRequestData, options?: any) {
return useRequest( (p: TRequestData) => request(p||requestData), options);
};
}
useRequest的类型一大堆泛型,又不导出这些类型,虽然Parameters和ReturnType能拿到类型,但又是<unknown>
这种泛型的。。。
😂过来看下大佬有没有试过,或者有别的封装方式
fjc0k commented
hhh,目前的一个项目也用的 @umijs/hooks,不过业务代码略杂乱而且定制化很强,你可以看看作为参考:
import baseRequest from './request'
import {DependencyList, useEffect} from 'react'
import {Request} from './index'
import {RequestConfig} from 'yapi-to-typescript'
import {useRequest as useUmiRequest, useUpdateEffect} from '@umijs/hooks'
export default function makeRequestHook<TRequestData, TRequestConfig extends RequestConfig, TRequestResult extends ReturnType<typeof baseRequest>>(request: Request<TRequestData, TRequestConfig, TRequestResult>) {
type Data = TRequestResult extends Promise<infer R> ? R : TRequestResult
const useRequestRequired = function useRequest(requestData: TRequestData | boolean | null | undefined | 0, deps: DependencyList = [], manual = false) {
const res = useUmiRequest<Data>(
(nextRequestData = requestData) => request(nextRequestData as any),
{
manual: true,
refreshOnWindowFocus: false,
},
)
useUpdateEffect(() => {
if (typeof requestData !== 'boolean' && requestData != null && requestData !== 0) {
res.run(requestData)
}
}, deps)
useEffect(() => {
if (!manual && typeof requestData !== 'boolean' && requestData != null && requestData !== 0) {
res.run(requestData)
}
}, [])
return res
}
const useRequestOptional = function useRequest(manual = false) {
const res = useUmiRequest<Data>(
request,
{
manual: true,
refreshOnWindowFocus: false,
},
)
useEffect(() => {
if (!manual) {
res.run()
}
}, [])
return res
}
return (
request.requestConfig.requestDataOptional
? useRequestOptional
: useRequestRequired
) as (
TRequestConfig['requestDataOptional'] extends true
? typeof useRequestOptional
: typeof useRequestRequired
)
}