[英]React - To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function
[英]state update on an unmounted component. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function
我正在嘗試在 FlatList 中使用 ListEmptyComponent
如果我沒有數據,我想顯示 ListEmptyComponent={}
但是,在Loadingsecoend組件中,我使用useEffect在加載為真時渲染,2秒后沒有數據,即加載為假時嘗試渲染..但如果我使用此代碼,則會發生此錯誤
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.
我明白是什么原因。 但我不知道我該如何解決......
這是我的代碼
(todoList.js)
return (
<FlatList
data={getComment}
keyExtractor={(item) => String(item.id)}
initialNumToRender={50}
ListEmptyComponent={<Loadingsecoend />}
renderItem={({item}) => (
<TodoItem
item={item}
/>
)}
/>
);
(加載second.js)
const Loadingsecoend = () => {
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
setTimeout(() => {
setLoading(false);
},2000);
},[]);
return (
loading ? (
<Container>
<ActivityIndicator color="#D3D3D3" size="large" />
</Container>
)
:(<Container>
<Label>no data</Label>
</Container>)
);
};
我該如何解決這個錯誤?
您應該在清理 function 中清除計時器。 該組件在超時到期之前由於某種原因正在卸載,因此您嘗試設置已卸載組件的 state。 調用從useEffect
掛鈎返回清理 function 以清理當前渲染周期中的任何效果。 當與具有空依賴項的useEffect
掛鈎一起使用時,它與componentWillUnmount
同義,換句話說,它在組件卸載之前運行。
useEffect(() => {
setLoading(true);
const timerId = setTimeout(() => {
setLoading(false);
}, 2000);
return () => clearTimeout(timerId);
}, []);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.