我正在從 axios 獲取資料。但有時資料即將到來,而有些資料最初并未顯示。
獲取特定的薪水-api.js :---
const AllSpecificSalaryAPI = (yearMonthFilter) => {
const [specificAllAPIData, setAllSpecificAPIData] = useState("");
const loginAuthToken = useSelector(
(state) => state.loginAuthTokenReducer.loginAuthToken
);
//NOTE:taking oved input and company selection code for dynamic parameter
const companyValue = useSelector(
(state) => state.changeCompanyReducer.company
);
const companyCode = companyValue[0];
const employeeId = companyValue[1];
useEffect(() => {
axios
.get(GET_ALL_SPECIFIC_SALARY, {
params: {
hev: companyCode,
year_month: yearMonthFilter,
oved: employeeId,
},
headers: {
Authorization: `Bearer ${loginAuthToken}`,
},
})
.then((response) => response.data)
.then((data) => setAllSpecificAPIData(data))
.catch((error) => {
if (error.status === 401) {
//NOTE: handling token expire
return ExpireAlertRestart();
} else {
Alert.alert(error.message);
}
});
}, []);
return {
specificAllAPI: specificAllAPIData,
};
};
export default AllSpecificSalaryAPI;
我收到警告訊息。
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
at [native code]:null in dispatchAction
at src/api/get-specific-salary-api.js:32:12 in axios.get.then.then$argument_0
我該如何解決此警告訊息?
uj5u.com熱心網友回復:
在你的 useEffect 中,像這樣清理你的狀態:
const [specificAllAPIData, setAllSpecificAPIData] = useState(null);
useEffect(() => {
return () => {
setAllSpecificAPIData(null);
};
}, []);
請在此處查看有關 useEffect 如何作業的更好解釋
uj5u.com熱心網友回復:
您之所以會出現這種情況,是因為update the state 即使組件已卸載,該組件也會嘗試執行此操作。
為了解決這個問題,您可以使用指示組件卸載的指示變數。在卸載時,它將攔截兩者之間的狀態更新請求并取消該請求。
let hasUnmounted = false;
useEffect(() => {
axios
.get(GET_ALL_SPECIFIC_SALARY, {
params: {
hev: companyCode,
year_month: yearMonthFilter,
oved: employeeId,
},
headers: {
Authorization: `Bearer ${loginAuthToken}`,
},
})
.then((response) => response.data)
.then((data) => {
if (hasUnmounted) return;
setAllSpecificAPIData(data)
})
.catch((error) => {
if (hasUnmounted) return;
if (error.status === 401) {
//NOTE: handling token expire
return ExpireAlertRestart();
} else {
Alert.alert(error.message);
}
});
return () => {
hasUnmounted = true;
}
}, []);
檢查此鏈接以進行實施:https : //codesandbox.io/s/happy-swartz-ikqdn?file=/src/updateErr.js
注:去https://ikqdn.csb.app/err中codesandbox's browser
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/376806.html
上一篇:如何使用變數查找物件鍵?
