我试图使喜欢/不喜欢的功能在反应,我面临的问题是,如果我试图喜欢/不喜欢的帖子,在其他的帖子喜欢/不喜欢按钮将加载状态。这意味着我喜欢一个帖子,但每个帖子喜欢按钮是加载。他们没有做任何仅仅是加载指示,因为有{isLoading ? }类型的状态。
这可能是我处理加载状态错误或任何其他。请有人帮忙,谁知道出了什么问题?

如果我想喜欢“嗨!”发邮件。就像"Hello“帖子的按钮开始加载。
这是我喜欢的按钮逻辑:
const [likeHandling, setLikeHandling] = useState(false);
const [posts, setPosts] = useState([]);
//This will fetch all posts
const getAllPost = async () => {
try {
setLoading(true);
const res = await axiosjwt.get(`${BASE_API_URL}/get-community-posts`);
setPosts(res.data);
console.log(res.data);
setLoading(false);
} catch (err) {
console.log(err);
setLoading(false);
}
};
//This will like or unlike post in this same endpoint and return that particualar post
const likePost = async (post_id, user_id, index) => {
try {
setLikeHandling(true);
const res = await axiosjwt.post(`${BASE_API_URL}/likehandle`, {
post_id,
});
console.log(res.data);
const updatedPosts = posts.map((post) => {
if (post._id == res.data._id) {
return res.data;
} else {
return post;
}
});
setPosts(updatedPosts);
setLikeHandling(false);
} catch (err) {
console.log(err);
setLikeHandling(false);
}
};
<button
disabled={likeHandling}
className="inline-flex justify-center items-center w-full hover:bg-gray-100 py-1"
onClick={() => likePost(post._id, user.User._id, index)}
>
<span className="mr-2">
{post.likes.includes(user.User._id.toString()) ? (
<>
<button disabled={likeHandling}>
{" "}
<AiFillLike
className={
likeHandling
? "w-6 h-6 text-blue-500 animate-bounce"
: "w-6 h-6 text-blue-500"
}
/>
</button>
</>
) : (
<button disabled={likeHandling}>
<AiOutlineLike
className={
likeHandling
? "w-6 h-6 text-gray-700 animate-bounce"
: "w-6 h-6 text-gray-700"
}
/>
</button>
)}
</span>
<span className="text-md font-bold">
{post?.likes ? post.likes.length : 1} Likes
</span>
</button>请提供一些帮助和建议,如果可以做任何改进?或者解决我的问题所需要的其他东西?
发布于 2022-06-28 13:02:14
代码的问题是,对于所有类似的按钮,只有一个加载标志。你需要按每个按钮加载标志。您应该创建一些具有自己的加载状态的<LikeButton />组件,然后在.map中使用<LikeButton />。你只需要把它往下移动一层,移到按钮层。还可以在map中使用键。
https://stackoverflow.com/questions/72786361
复制相似问题