我嘗試獲取專案資料。如果請求回應小于 1,我必須再次請求。所以我用setTimeout寫了一個遞回函式。但是當我嘗試更改我的路線功能時,它會繼續作業。卸載組件時,window.clearTimeout() 或 global.clearTimeOut() 在這里不起作用。我想念什么嗎?
useEffect(() => {
getItems(params);
return () => {
window.clearTimeout();
global.clearTimeout();
}
}, []);
const getItems = async(params) => {
try {
const { data = []} = await axios.get('/some-endpoint',params);
dispatch({ type: ITEMS_START });
if (data.length === 0) {
setTimeout(() => {
getItems(params);
}, 5000);
} else {
dispatch({ type: ITEMS_SUCCESS, payload: { data } });
}
} catch (error) {
dispatch({ type: ITEMS_ERROR, payload: error });
}
}
uj5u.com熱心網友回復:
使用 ref 存盤timeout ID然后清除該超時。
const timeoutRef = React.useRef();
useEffect(() => {
getItems(params);
return () => {
window.clearTimeout(timeoutRef.current);
}
}, []);
const getItems = async(params) => {
try {
const { data = []} = await axios.get('/some-endpoint',params);
dispatch({ type: ITEMS_START });
if (data.length === 0) {
timeoutRef.current = setTimeout(() => {
getItems(params);
}, 5000);
} else {
dispatch({ type: ITEMS_SUCCESS, payload: { data } });
}
} catch (error) {
dispatch({ type: ITEMS_ERROR, payload: error });
}
}
uj5u.com熱心網友回復:
創建一個參考,您也可以設定超時,卸載可以回呼。
let timeout = null;
useEffect(() => {
getItems();
return () => {
if(timeout)
clearTimeOut(timeout)
}
})
const getItems = () => {
timeout = setTimeOut(() => work, 5000);
}
這是一般的想法。
uj5u.com熱心網友回復:
每個 SetTimeout (和 setInterval )都回傳一個可用于清除它的數字。即,var x = setTimeout(() => console.log('timeout'),1000); clearTimeout(x);什么也不做。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/492068.html
標籤:javascript
下一篇:“getWatchLength”未在實體上定義,但在渲染期間被參考。確保在data選項中宣告反應資料vuejs屬性
