【发布时间】:2021-03-21 08:44:57
【问题描述】:
我有以下 http 钩子:
export const useHttp = <T,>(initUrl: string, initData: T) => {
const [url, setUrl] = useState(initUrl);
const [state, dispatch] = useReducer(fetchReducer, {
isLoading: false,
error: '',
data: initData
});
useEffect(() => {
let cancelRequest = false;
const fetchData = async (cancelRequest: boolean = false) => {
if (!url) return;
dispatch({ type: 'API_REQUEST'});
try {
const responsePromise: AxiosPromise<T> = axios(url);
const response = await responsePromise;
if (cancelRequest) return;
dispatch({ type: 'API_SUCCESS', payload: response.data });
} catch (e) {
console.log("Got error", e);
dispatch({ type: 'API_ERROR', payload: e.message });
}
};
fetchData(cancelRequest);
return () => {
cancelRequest = true;
}
}, [url]);
const executeFetch = (url: string) => {
setUrl(url);
};
return { ...state, executeFetch}
};
减速机:
const fetchReducer = <T,>(state: IState<T>, action: TAction<T>): IState<T> => {
switch (action.type) {
case 'API_REQUEST':
return {
...state,
isLoading: true
};
case 'API_SUCCESS':
return {
...state,
data: action.payload,
isLoading: false,
error: ''
};
case 'API_ERROR':
console.error(`Triggered: ${API_ERROR}, message: ${action.payload}`);
return {
...state,
error: action.payload,
isLoading: false,
};
default:
throw Error('Invalid action');
}
};
行动:
export interface IApiSuccess<T> {
type: types.ApiSuccess,
payload: T;
}
export type TAction<T> = IApiRequest | IApiSuccess<T> | IApiError;
这样使用:
const { data, error, isLoading, executeFetch } = useHttp<IArticle[]>('news', []);
return (
<>
<div className={classes.articleListHeader}>
<h1>Article List</h1>
<small className={classes.headerSubtitle}>{data.length} Articles</small>
</div>
<ul>
{data.map(article => <Article article={article}/>)}
</ul>
</>
)
我的 TS 对我大喊大叫,因为我正在使用 data 变量:Object is of type 'unknown'. TS2571
我确实指定了 useHttp 的类型,即 IArtlce[]。 知道我缺少什么吗?
更新: 我试图为我的减速器添加返回类型:
interface HttpReducer<T> extends IState<T> {
executeFetch: (url: string) => void
}
export const useHttp = <T,>(initUrl: string, initData: T): HttpReducer<T> => {
但我明白了:
Type '{ executeFetch: (url: string) => void; error: string; isLoading: boolean; data: unknown; }' is not assignable to type 'HttpReducer<T>'.
【问题讨论】:
-
尝试将类型添加到
state。或者向自定义钩子添加返回类型。 -
在
state中添加类型是什么意思?我的状态参数有IState<T>类型。 -
问题中没有提到...您是否尝试添加返回类型?
-
fetchReducer是如何输入的? -
@RameshReddy 不确定如何为我的案例添加这种类型。用示例更新了我的问题
标签: reactjs typescript react-hooks typescript-generics use-reducer