斯蒂芬大帝
2023-05-25 16:33:14
我正在向我的數據庫發出 GET 請求,數據正在進入并顯示,但是當數據在我的數據庫上更新時,它不會在使用該數據的組件上更新。編輯 根據我需要不斷發出 GET 請求的評論,所以我更新了問題。useEffect() 設置數據狀態// Data for each of the tagsconst [tag1, setTag1] = useState();const [tag2, setTag2] = useState();const [tag3, setTag3] = useState();useEffect(() => { axios .get(URL) .then(res => { const data = res.data; // Passing in the setter method setTagDetails(data, setTag1, setTag2, setTag3); }) .catch(error => { console.log(error); });}, []);setTagDetails() 其中傳入的數據被分成不同的狀態以在組件中使用:// Splitting the data by each corresponding tag and adding them to their respective stateexport const setTagDetails = (data, setTag1, setTag2, setTag3) => { const arr1 = []; const arr2 = []; const arr3 = []; try { data && data.forEach(d => { // Entries into the database which do not have any tag information // have a size of 5 and those with all the details have a size of 6 const sizeOfObject = Object.keys(d).length; // Only need database items with all the details if (sizeOfObject > 5) { // Split the data for the tags into their respective name const name = d["tags"]["L"][0]["M"]["name"]["S"]; // Will be used to set individual datasets for each tag if (name === "Tag1") { cleanTag(d, arr1); } if (name === "Tag2") { cleanTag(d, arr2); } if (name === "Tag3") { cleanTag(d, arr3); } } }); setTag1(arr1); setTag2(arr2); setTag3(arr3); } catch (err) { console.log(err); }};
1 回答

qq_花開花謝_0
TA貢獻1835條經驗 獲得超7個贊
當你想每隔 x 時間執行一個函數時,我們使用setInterval 方法。它將每隔 x 毫秒調用傳入的函數(作為第一個參數)(其中 x 是第二個參數,在下面的示例中為 1000 毫秒或 1 秒)。
useEffect(() => {
const interval = setInterval(() => {
? ?axios
? ? .get(URL)
? ? .then(res => {
? ? ? ? const data = res.data;
? ? ? ? // Passing in the setter method
? ? ? ? setTagDetails(data, setTag1, setTag2, setTag3);
? ? })
? ? .catch(error => {
? ? ? ? console.log(error);
? ? });
? }, 1000);
? return () => clearInterval(interval);
}, []);
請注意,在移動網絡速度較慢或 ISP 政策帶寬受限的情況下,最好注意用戶的互聯網連接。將請求如此緊密地運行在一起也有危險,以至于我們引入了競爭條件。最后,您必須清除間隔,否則會嚴重影響應用程序的性能。
添加回答
舉報
0/150
提交
取消