我正在尝试在 FlatList 中使用 ListEmptyComponent
如果我没有数据,我想显示 ListEmptyComponent={}
但是,在 Loadingsecoend 组件中,当加载为 true 时我使用 useEffect 进行渲染,并且在 2 秒后没有数据,即当加载为 false 时尝试渲染..但如果我使用此代码,则会出现此错误
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}
/>
)}
/>
);
(Loadingsecond.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>)
);
};
我该如何解决这个错误?
答案 0 :(得分:1)
您应该在清理函数中清除计时器。由于某种原因,组件正在卸载在超时到期之前,因此您正在尝试设置卸载组件的状态。调用从 useEffect
钩子返回清理函数以清理当前渲染周期中的任何效果。当与具有空依赖关系的 useEffect
钩子一起使用时,它与 componentWillUnmount
同义,换句话说,它在组件卸载之前运行。
useEffect(() => {
setLoading(true);
const timerId = setTimeout(() => {
setLoading(false);
}, 2000);
return () => clearTimeout(timerId);
}, []);