【问题标题】:state update on an unmounted component. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function未安装组件的状态更新。要修复,请取消 useEffect 清理函数中的所有订阅和异步任务
【发布时间】:2021-03-10 08:17:09
【问题描述】:

我正在尝试在 FlatList 中使用 ListEmptyComponent

如果我没有数据我想显示 ListEmptyComponent={}

但是,在 Loadingsecoend 组件中,我使用 useEffect 在加载为 true 时进行渲染,并且 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}
                    
                    />
                )}

                />
            );

(加载第二个.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>)
            
            );
            };

我该如何解决这个错误?

【问题讨论】:

    标签: javascript node.js reactjs react-native


    【解决方案1】:

    您应该在清理函数中清除计时器。由于某种原因超时到期之前卸载组件,因此您正在尝试设置已卸载组件的状态。从useEffect 挂钩返回清理函数被调用以清理当前渲染周期中的任何效果。当与具有空依赖项的 useEffect 挂钩一起使用时,它与 componentWillUnmount 同义,换句话说,它在组件卸载之前运行。

    useEffect(() => {
      setLoading(true);
      const timerId = setTimeout(() => {
        setLoading(false);
      }, 2000);
    
      return () => clearTimeout(timerId);
    }, []);
    

    【讨论】:

      猜你喜欢
      • 2019-10-20
      • 2021-03-24
      • 2021-06-23
      • 2020-03-31
      • 2021-01-28
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      相关资源
      最近更新 更多