gpt4 book ai didi

reactjs - 使用 Firebase 和 React 的 useEffect 清理功能

转载 作者:行者123 更新时间:2023-12-02 02:26:39 29 4
gpt4 key购买 nike

我有一个问题,我的 useEffect 导致了以下警告:

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.

此问题仅在从该组件处于事件状态的页面开始重新加载页面时出现。

该组件运行良好,但警告看起来很糟糕。

我看过多个帖子,其中使用清理功能应该有效,并尝试应用,但它一直给我同样的警告。

有什么线索吗?

import React, { useState, useEffect } from 'react'
import ImageGallery from 'react-image-gallery';
import "./ImageGal.css"
import "react-image-gallery/styles/css/image-gallery.css";
import fire from "./firebase";

function ImageGal({ unique }) {

const [images, setImages] = useState([]);

useEffect(() => {
const fetchImages = async () => {
const response = fire.firestore().collection("albums/" + unique + "/images"); //unique is the name of the album, passed on as a prop to this component
const data = await response.get();
const Imagearray = [];

data.docs.forEach(item => {
Imagearray.push({ id: item.id, original: item.data().url })
})
setImages(Imagearray)
}

fetchImages();

}, [])


return (
<div className="imagegal">

<ImageGallery
infinite={true}
lazyLoad={true} items={images} showThumbnails={false}
slideInterval={4000}

/>
</div>
)
}

export default ImageGal

最好的问候,奥斯卡

最佳答案

问题是组件卸载了,但您尝试在那之后设置状态。防止这种情况的最简单方法是将 isMounted 变量设置为 true,在您的清理函数中,您设置为 false。然后,仅当该变量为 true 时才在效果中设置状态。

useEffect(() => {
let isMounted = true;

const fetchImages = async () => {
const response = fire
.firestore()
.collection("albums/" + unique + "/images"); //unique is the name of the album, passed on as a prop to this component
const data = await response.get();
const Imagearray = [];

data.docs.forEach((item) => {
Imagearray.push({ id: item.id, original: item.data().url });
});

if (isMounted) setImages(Imagearray);
};

fetchImages();

return () => {
isMounted = false;
};
}, []);

关于reactjs - 使用 Firebase 和 React 的 useEffect 清理功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65551682/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com