我已經將 SWR 包裝成一個自定義鉤子:
import useSWR from 'swr';
export enum MethodTypes {
POST = 'POST',
PUT = 'PUT',
GET = 'GET',
DELETE = 'DELETE',
PATCH = 'PATCH'
}
type QueryBody = {
method: MethodTypes;
body: Object;
};
const useFetch = <T>(url: string, dataObj: QueryBody) => {
const fetcher = async () => {
return await fetch(url, {
method: dataObj.method,
body: JSON.stringify(dataObj.body)
}).then((res) => {
return res.json();
});
};
const { data, error } = useSWR<T>(fetcher);
return {
data,
error
};
};
export default useFetch;
我稱之為:
const { data } = useFetch<Cart>('myUrl', {
method: MethodTypes.POST,
body: {
myBodyObj
}
});
購物車型別:
export type Cart = {
cartId: string;
items: Array<CartItem>;
};
我可以看到我收到了 200 回應,因此呼叫通過,但我的資料始終未定義。我在這里錯過了什么?
uj5u.com熱心網友回復:
useSWR的第一個引數應該是關鍵。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/398176.html
標籤:javascript 反应 打字稿 反应钩子 变频
