当我创建保存用户帖子以在 UI 上呈现的创建帖子状态时,我在该状态中创建了一个 addPost 函数,该函数对要在个人资料页面上的用户名下方呈现的帖子进行计数。在我创建删除计数的删除帖子功能之前,我通过创建几个帖子并删除它们来测试代码的功能。现在,当我创建该功能时,它按计划工作,但我的状态记得之前的两篇帖子尚未被删除。我的用户有 3 个帖子,但显示为 5 个。如何重置我的状态?
我尝试创建一个函数,将我的帖子重置为空数组,并将其添加到我的 getUserPosts 中,但结果是个人资料页面的加载时间非常糟糕。这是相关代码。
统计帖子的州:
import { create } from "zustand"
const useUserProfileStore = create((set) => ({
userProfile: null,
setUserProfile: (userProfile) => set({ userProfile }),
//UPDATE the number of posts
addPost: (post) => set(state => ({
//Ubiti ono spreada postove usera i dodaje jos jedan id u post
userProfile: { ...state.userProfile, posts: [post.id, ...state.userProfile.posts] }
})),
deletePost: (id) => set((state) => ({
userProfile: {
...state.userProfile,
posts: state.userProfile.posts.filter((post) => post.id !== id)
}
})),
}))
export default useUserProfileStore;
获取帖子并将其传递给组件的钩子:
import { useEffect, useState } from 'react';
import useShowToast from './useShowToast'
import usePostStore from '../store/postStore';
import useUserProfileStore from '../store/userProfileStore';
import { collection, getDocs, query, where } from 'firebase/firestore';
import { firestore } from '../Firebase/firebase';
const useGetUserPosts = () => {
const showToast = useShowToast();
const [isLoading, setIsLoading] = useState(true);
const { posts, setPosts } = usePostStore();
const userProfile = useUserProfileStore(state => state.userProfile);
useEffect(() => {
const getPosts = async () => {
if (!userProfile) return
setIsLoading(true);
setPosts([]);
try {
const q = query(collection(firestore, "posts"), where("createdBy", "==", userProfile.uid))
const querySnapshot = await getDocs(q)
const post = [];
querySnapshot.forEach((doc) => {
post.push({ ...doc.data(), id: doc.id })
});
//Sort by latest post (latest on top)
post.sort((a, b) => b.createdAt - a.createdAt);
setPosts(post);
} catch (error) {
showToast("Error", error.message, "error");
setPosts([])
} finally {
setIsLoading(false);
}
}
getPosts();
}, [setPosts, userProfile, showToast])
return { isLoading, posts }
}
export default useGetUserPosts;
看起来基于 ID 进行过滤的逻辑可能无法正常工作,因此陈旧数据永远不会被真正过滤掉。
您可以尝试打印出传递到删除帖子的 id 并验证该 id 是否也存在于 state.userProfile.posts 列表中?
deletePost: (id) =>
set((state) => {
console.log("Deleting post with id:", id);
console.log("Posts before deletion:", state.userProfile.posts);
const updatedPosts = state.userProfile.posts.filter((post) => post.id !== id);
console.log("Posts after deletion:", updatedPosts);
return {
userProfile: {
...state.userProfile,
posts: updatedPosts,
},
};
}),
您可以添加这些打印语句来告诉我您是否看到 state.userProfile.posts 中存在正确的 ID?