2 回答

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超7個贊
如果您還不知道 - 您可以在 useEffect 鉤子的末尾返回一個函數(shù)。每當(dāng)該效果再次觸發(fā)時(例如,當(dāng)其依賴項(xiàng)的值發(fā)生變化時),以及在組件卸載之前,都會調(diào)用該函數(shù)。所以如果你有一個像這樣的 useEffect 鉤子:
useEffect(() => {
// logic here
return () => {
// clean up
};
}, []); // no dependencies!
相當(dāng)于:
class SomeComponent extends React.Component {
componentDidMount() {
// logic here
}
componentWillUnmount() {
// clean up
}
}
所以在你的代碼中我會添加這個:
useEffect(() => {
let isCancelled = false;
const fetchData = async () => {
try {
// fetch logic omitted...
const data = await AsyncStorage.getItem(STORAGE_KEY);
if (storedThemeID) setThemeID(storedThemeID);
else setThemeID(THEMES[1].key);
} catch (e) {
throw new Error(e)
}
};
fetchData();
return () => {
isCancelled = true;
};
}, [themeID]);

TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個贊
試試這個
let unmounted = false;
useEffect(() => {
(async () => {
const storedThemeID = await AsyncStorage.getItem(STORAGE_KEY);
if (!unmounted) {
if (storedThemeID) setThemeID(storedThemeID);
else setThemeID(THEMES[1].key);
}
})();
return () => {
unmounted = true;
};
}, []);
添加回答
舉報(bào)