英文:
Change Like Button If Signed In User Already Liked A Post
问题
我希望一切都好。我正在尝试使用按钮来喜欢其他用户发布的帖子/文章。我创建了一个名为"getAPostLikeRecord()"的常量函数,它将返回喜欢单个帖子的用户列表。但是,如果当前登录的用户喜欢这篇文章,我希望喜欢按钮以不同的颜色突出显示。否则,它将保持当前的颜色。为了减少混淆,我想知道已登录的用户是否已经喜欢了一篇帖子,并且能够让已登录的用户知道帖子已经被喜欢了。
import React, { useEffect, useState } from "react";
import './Home.css';
//Components
import Header from '../../Components/Header/Header';
import Footer from '../../Components/Footer/Footer';
//Dependencies
import Axios from 'axios';
import { useNavigate, useLocation, useParams } from 'react-router-dom';
//Function
import VerificationCheck from "../../Functions/VerificationCheck";
const Home = () => {
// ... 省略了其他部分的代码
const getAPostLikeRecord = async (PostID) => {
const url = process.env.REACT_APP_Backend_URL + '/post/get-like-record';
await Axios.post(url, { PostsID: PostID })
.then((response) => {
setLikes(response.data);
if (response.data.length !== 0) {
for (var i = 0; i < response.data.length; i++) {
response.data[i].didUserLike = false;
}
const current_state = [...likes];
const current_likes = current_state.find(l => l.postsLikeAuthor.trim() === loggedInUser);
console.log(current_likes)
if (!current_likes) {
// couldn't find the post, ID's don't match
return;
}
// replace the current state to the opposite
current_likes.didUserLike = !current_likes.didUserLike;
setLikes(current_state);
}
})
.catch((error) => {
setStatusMessage("Server Side Error");
});
}
// ... 继续其他部分的代码
return (
<>
<Header />
<div className='homeBody'>
<div className="homeForm">
{/* ... */}
</div>
</div>
<Footer />
</>
);
}
export default Home;
更新:
我已经更新了我的代码中的getAPostLikeRecord()函数,以更改用户是否已经喜欢帖子的个别喜欢按钮的颜色。然而,.find 函数之前返回 undefined 的原因可能是没有匹配的项。您可以尝试在设置 current_likes 之前添加一个条件,以检查是否找到匹配的项,如下所示:
const current_likes = current_state.find(l => l.postsLikeAuthor.trim() === loggedInUser);
if (!current_likes) {
// couldn't find the post, ID's don't match
return;
}
// replace the current state to the opposite
current_likes.didUserLike = !current_likes.didUserLike;
setLikes(current_state);
这将确保只有在找到匹配项时才尝试更新状态。希望这可以帮助您解决问题。
英文:
I hope that all is well. I am trying to use a button to like a post/article posted by other users. I have created a const function called "getAPostLikeRecord()," which will return a list of users that like the individual post. However, if the user currently signed in liked the article, I would like to have the like button highlighted in a different color. Otherwise, it'll be the current color that it is. To be less confusing, I would like to know if the signed-in user already like a post and be able to let the signed-in user know that the post was already liked.
import React, { useEffect, useState } from "react";
import './Home.css'
//Components
import Header from '../../Components/Header/Header';
import Footer from '../../Components/Footer/Footer';
//Dependencies
import Axios from 'axios';
import { useNavigate, useLocation, useParams } from 'react-router-dom';
//Function
import VerificationCheck from "../../Functions/VerificationCheck";
const Home = () => {
const navigate = useNavigate();
const location = useLocation();
const userLoggedIn = VerificationCheck.CheckLogin();
const loggedInUser = VerificationCheck.CheckUser();
const [isLoading, setIsLoading] = useState(false);
const [posts, setPost] = useState([]);
const [likes, setLikes] = useState([]);
const [statusMessage, setStatusMessage] = useState(null);
useEffect(() => {
setIsLoading(true);
if (!userLoggedIn) {
navigate('/Login', {
state: {
previousUrl: location.pathname,
}
});
}
else {
getAllPost();
}
setIsLoading(false);
}, [userLoggedIn]);
const getAllPost = () => {
const url = process.env.REACT_APP_Backend_URL + '/post/get-post-record';
Axios.post (url)
.then ((response) => {
const _data = response.data;
for (var i = 0; i < _data.length; i++){
_data[i].displayMore = false;
}
setPost(_data);
})
.catch((error) => {
setStatusMessage("Server Side Error");
});
}
const getAPostLikeRecord = async (PostID) => {
const url = process.env.REACT_APP_Backend_URL + '/post/get-like-record';
await Axios.post (url, {PostsID : PostID})
.then ((response) => {
setLikes(response.data);
})
.catch((error) => {
setStatusMessage("Server Side Error");
});
}
const handleShowMore = (post_id) => {
const current_state = [...posts];
const current_post = current_state.find(p => p.postsID === post_id);
if(!current_post) {
// couldn't find the post, ID's dont match
return;
}
// replace the current state to the opposite
current_post.displayMore = !current_post.displayMore;
setPost(current_state);
}
const CommentRedirect = (postsID) => {
navigate(`/Post/${postsID}`);
}
return (
<>
<Header/>
<div className='homeBody'>
<div className="homeForm">
{isLoading ?
<>
<h1>Loading...</h1>
</>
:
<>
{statusMessage ?
<>
<h1>{statusMessage}</h1>
</>
:
<>
{posts.map(uploadedPost => (
<table key={uploadedPost.postsID}>
<tbody className="postData" key={uploadedPost.postsID}>
<tr><td><a href={`/Post/${uploadedPost.postsID}`}><h1 className="title">{uploadedPost.postsTitle}</h1></a></td></tr>
<tr>
<td>
<div className="authorDate">
<h2 className="author">Author: {uploadedPost.postsAuthor}</h2>
<h3 className="datetime">{uploadedPost.createdOn}</h3>
</div>
</td>
</tr>
<tr><td className="btn"><button className="btn" onClick={() => handleShowMore(uploadedPost.postsID)}>{uploadedPost.displayMore ? "Show less" : "Show more"}</button></td></tr>
<tr><td><p className="caption">{uploadedPost.displayMore ? uploadedPost.postsCaption : `${uploadedPost.postsCaption.substring(0, 250)}`}{uploadedPost.displayMore ? "" : "..."}</p></td></tr>
<tr><td><button className="interaction">{uploadedPost.postsLikes} Likes</button> <button className="interaction" onClick={() => CommentRedirect(uploadedPost.postsID)}>{uploadedPost.postsComments} Comment</button> <button className="interaction">Share</button></td></tr>
</tbody>
</table>
))}
</>
}
</>
}
</div>
</div>
<Footer />
</>
);
}
export default Home;
UPDATE:
I have updated the getAPostLikeRecord() function in my code to change the color of the individual-like button for a post if the user has already liked a post. However, .find is returning as undefined for some reason...
const getAPostLikeRecord = async (PostID) => {
const url = process.env.REACT_APP_Backend_URL + '/post/get-like-record';
await Axios.post (url, {
PostsID : PostID
})
.then ((response) => {
setLikes(response.data);
if (response.data.length !== 0) {
for (var i = 0; i < response.data.length; i++){
response.data[i].didUserLike = false;
}
const current_state = [...likes];
const current_likes = current_state.find(l => l.postsLikeAuthor.trim() === loggedInUser);
console.log(current_likes)
if(!current_likes) {
// couldn't find the post, ID's dont match
return;
}
// replace the current state to the opposite
current_likes.didUserLike = !current_likes.didUserLike;
setLikes(current_state);
}
})
.catch((error) => {
setStatusMessage("Server Side Error");
});
}
答案1
得分: 0
我可以想到两种方法来实现这个,不幸的是,两种方法都需要一些后端和数据库的更改,最简单的方法是将点赞记录设置如下:
{
likes: [userId: string]
}
然后在后端中,您可以通过检查请求中的 likes 数组是否包含 userId 来返回一个 "liked" 布尔值。
另一种方法是添加一个 likedPosts 表,然后检查当前帖子是否在 likedPosts 中:
{
likedPosts: [postId: string]
}
英文:
I can think of two ways to do this, sadly both require some backend and db changes and the easiest one is to set the likes record as follows:
{
likes: [userId: string]
}
and in your back-end you can return a "liked" boolean by checking if the likes array contains the userId in the request.
The other way is to add a likedPosts table, and then check if the current post is in that likedPosts.
{
likedPosts: [postId: string]
}
答案2
得分: 0
总的来说,您应该为用户提供一个包含他们喜欢的帖子的列,同时为帖子提供一个包含喜欢它的用户的列。这有点复杂但又简单。
一个帖子有一个喜欢它的用户列表。
一个用户有一个他们喜欢的帖子列表。
通过关注不同方面的分离,其他用户可以知道一篇帖子有多少个喜欢,而用户可以知道他们喜欢哪些帖子。
我假设您可以在后端控制实现,但如果您不能,而只能通过前端接近它,那么结果可能不太理想。
英文:
Overall, you should give a user a column containing posts they like while also giving a post a column containing users who like it. It’s a bit complicated but yet simple.
> A post has a list of users who like it.
> A user has a list of posts they like.
With the separation of concerns, other users can know how many likes a post has while a user can know which posts they like.
I assumed you can control the implementation on the backend but if you can’t but will only approach it via the frontend, it won’t turn out well.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论