我想創建一個自定義掛鉤,允許我隨時獲取一些資料。鉤子應該回傳一個函式,我可以在我的代碼中的任何地方呼叫它來獲取資料,以及一個保存回應的變數。此外,它應該將獲取的狀態回傳給我。
我的鉤子看起來像這樣:
import React, { useState } from "react";
import { AppListResponse } from "../../typings/AppListResponse";
const useFetchAppList = (
userId: string,
authToken: string
): [() => Promise<void>, (value: React.SetStateAction<string>) => void, string, AppListResponse | null | undefined] => {
const [status, setStatus] = useState<string>("idle");
const [responseData, setData] = useState<AppListResponse | null>();
const url = `https://my-endpoint.com/lets-fetch-this`;
const options = {
method: "GET",
headers: {
CustomAuthToken: authToken,
UserID: userId,
Accept: "application/json",
"Content-Type": "application/json"
}
};
const fetchAppList = async (): Promise<void> => {
setStatus("fetching");
try {
const response = await fetch(url, options);
const json = await response.json();
setData(json);
setStatus("successful");
} catch (error) {
console.log("error", error);
}
};
return [fetchAppList, setStatus, status, responseData];
};
export default useFetchAppList;
我試著這樣稱呼它:
const [fetchAppList, setStatus, status, data] = useFetchAppList(userId, authToken);
useEffect(() => {
const fetchData = async (): Promise<void> => {
await fetchAppList();
};
fetchData();
console.log(data, status);
}, []);
問題在于,console.log(data)returnsundefined和thestatus具有它開頭的默認值,即idle.
我怎樣才能做到這一點,以便我可以fetchAppList()在需要時呼叫,從而回傳我需要的資料?
uj5u.com熱心網友回復:
在組件檔案(第二個代碼,您正在呼叫的地方useFetchAppList )中,您需要捕獲指定的data和status之外的useEffect內容。在useEffect你的代碼的運行只在最初一次渲染和它記住(關閉)的值data,并status在當時被呼叫。最初設定為undefined和"idle"由鉤子useFetchAppList。
要查看實際發生的情況,請將以下代碼也添加到您的第二個檔案中
useEffect(() => {
console.log(data, status);
});
您將看到不同的控制臺專案。首先它會是"idle"然后它應該是"fetching"最后它會是"successful" or "error"
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/372377.html
標籤:javascript 反应 打字稿 反应钩子
上一篇:帶有文本欄位的多個復選框
