每当我打开某人的图像时,反应状态更新错误,并且图像也不会重新生成。如何修复此错误



我正在创建一个类似snapchat的web应用程序,这是一个聊天页面,不同用户可以在其中执行所有不同的快照,但当我打开他们的快照时,他们的图像不会呈现,我总是以这个错误结束-

警告:无法对未安装的组件执行React状态更新。这是一个非操作,但它表明应用程序中存在内存泄漏。若要修复此问题,请取消useEffect清理函数中的所有订阅和异步任务。在Chats

import "./Chats.css";
import { Avatar } from "@material-ui/core";
import SearchIcon from "@material-ui/icons/Search";
import ChatBubbleIcon from "@material-ui/icons/ChatBubble";
import { auth, db } from "./firebase";
import Chat from "./Chat";
import { useDispatch, useSelector } from "react-redux";
import { selectUser } from "./features/appSlice";
import RadioButtonUncheckedIcon from "@material-ui/icons/RadioButtonUnchecked";
import { useHistory } from "react-router";
import { resetCameraImage } from "./features/cameraSlice";
const Chats = () => {
const [posts, setPosts] = useState([]);
const user = useSelector(selectUser);
const dispatch = useDispatch();
const history = useHistory();
useEffect(() => {
db.collection("posts")
.orderBy("timestamp", "desc")
.onSnapshot((snapshot) =>
setPosts(
snapshot?.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
)
);
}, []);
const takeSnap = () => {
dispatch(resetCameraImage());
history.pushState("/");
};
return (
<div className="chats">
<div className="chats__header">
<Avatar
className="chats__avatar"
src={user.propilePic}
onClick={() => auth.signOut()}
/>
<div className="chats__search">
<SearchIcon className="chats__searchIcon" />
<input placeholder="Friends" type="text" />
</div>
<ChatBubbleIcon className="chats__chatIcon" />
</div>
<div className="chats__posts">
{posts.map(
({
id,
data: { profilePic, username, timestamp, imageUrl, read },
}) => (
<Chat
key={id}
id={id}
profilePic={profilePic}
username={username}
timestamp={timestamp}
imageUrl={imageUrl}
read={read}
/>
)
)}
</div>
<RadioButtonUncheckedIcon
className="chats_takePicIcon"
onClick={takeSnap}
fontSize="large"
/>
</div>
);
};
export default Chats;```

这个问题与onSnapshot函数为组件订阅实时Firebase更新有关,即使组件已卸载,因此您必须在useEffect上返回一个取消订阅函数,如下所示:

useEffect(() => {
const unsubscribe = db.collection("posts")
.orderBy("timestamp", "desc")
.onSnapshot((snapshot) =>
setPosts(
snapshot?.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
)
);
return () => unsubscribe();
}, []);

最新更新