【发布时间】:2022-06-28 21:02:14
【问题描述】:
我正在尝试在 react 中创建喜欢/不喜欢的功能,我面临的问题是,如果我尝试喜欢/不喜欢任何帖子,那么在每个其他帖子中,喜欢/不喜欢按钮都会进入加载状态。意味着我喜欢一个帖子,但每个帖子都喜欢按钮正在加载。他们没有做任何事情,只是加载指示,因为存在 {isLoading ? } 那种状态。
这可能是我处理加载状态错误或任何其他问题。请知道发生了什么问题的人帮忙?
如果我想喜欢“你好!”邮政 。 “你好”帖子的点赞按钮开始加载。
这是我喜欢的按钮逻辑:
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>
请一些帮助和建议是否可以做任何改进?或者解决我的问题需要什么其他的东西?
【问题讨论】:
-
如果有人看不懂是怎么处理的? : likeHandling 有点像 isLoading 的 like/dislike 。 Tq❤️
标签: javascript reactjs express react-context