如果已登录用户已经点赞了一篇帖子,请更改“喜欢”按钮。

huangapple go评论63阅读模式
英文:

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 &quot;react&quot;;
import &#39;./Home.css&#39;
//Components
import Header from &#39;../../Components/Header/Header&#39;;
import Footer from &#39;../../Components/Footer/Footer&#39;;
//Dependencies
import Axios from &#39;axios&#39;;
import { useNavigate, useLocation, useParams } from &#39;react-router-dom&#39;;
//Function
import VerificationCheck from &quot;../../Functions/VerificationCheck&quot;;
const Home = () =&gt; {
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(() =&gt; {
setIsLoading(true);
if (!userLoggedIn) {
navigate(&#39;/Login&#39;, {
state: {
previousUrl: location.pathname,
}
});
}
else {
getAllPost();
}
setIsLoading(false);
}, [userLoggedIn]);
const getAllPost = () =&gt; {
const url = process.env.REACT_APP_Backend_URL + &#39;/post/get-post-record&#39;;
Axios.post (url)
.then ((response) =&gt; {
const _data = response.data;
for (var i = 0; i &lt; _data.length; i++){
_data[i].displayMore = false;
}
setPost(_data);
})
.catch((error) =&gt; {
setStatusMessage(&quot;Server Side Error&quot;);
});
}
const getAPostLikeRecord = async (PostID) =&gt; {
const url = process.env.REACT_APP_Backend_URL + &#39;/post/get-like-record&#39;;
await Axios.post (url, {PostsID : PostID})
.then ((response) =&gt; {
setLikes(response.data);
})
.catch((error) =&gt; {
setStatusMessage(&quot;Server Side Error&quot;);
});
}    
const handleShowMore = (post_id) =&gt; {
const current_state = [...posts];
const current_post = current_state.find(p =&gt; p.postsID === post_id);
if(!current_post) {
// couldn&#39;t find the post, ID&#39;s dont match
return;
}
// replace the current state to the opposite
current_post.displayMore = !current_post.displayMore;
setPost(current_state);
}
const CommentRedirect = (postsID) =&gt; {
navigate(`/Post/${postsID}`);
}
return (
&lt;&gt;
&lt;Header/&gt;
&lt;div className=&#39;homeBody&#39;&gt;
&lt;div className=&quot;homeForm&quot;&gt;
{isLoading ?
&lt;&gt;
&lt;h1&gt;Loading...&lt;/h1&gt;
&lt;/&gt;
:
&lt;&gt;
{statusMessage ? 
&lt;&gt;
&lt;h1&gt;{statusMessage}&lt;/h1&gt;
&lt;/&gt;
:
&lt;&gt;
{posts.map(uploadedPost =&gt; (
&lt;table key={uploadedPost.postsID}&gt;
&lt;tbody className=&quot;postData&quot; key={uploadedPost.postsID}&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href={`/Post/${uploadedPost.postsID}`}&gt;&lt;h1 className=&quot;title&quot;&gt;{uploadedPost.postsTitle}&lt;/h1&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;div className=&quot;authorDate&quot;&gt;
&lt;h2 className=&quot;author&quot;&gt;Author: {uploadedPost.postsAuthor}&lt;/h2&gt;
&lt;h3 className=&quot;datetime&quot;&gt;{uploadedPost.createdOn}&lt;/h3&gt;
&lt;/div&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;&lt;td className=&quot;btn&quot;&gt;&lt;button className=&quot;btn&quot; onClick={() =&gt; handleShowMore(uploadedPost.postsID)}&gt;{uploadedPost.displayMore ? &quot;Show less&quot; : &quot;Show more&quot;}&lt;/button&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;p className=&quot;caption&quot;&gt;{uploadedPost.displayMore ? uploadedPost.postsCaption : `${uploadedPost.postsCaption.substring(0, 250)}`}{uploadedPost.displayMore ? &quot;&quot; : &quot;...&quot;}&lt;/p&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;button className=&quot;interaction&quot;&gt;{uploadedPost.postsLikes} Likes&lt;/button&gt; &lt;button className=&quot;interaction&quot; onClick={() =&gt; CommentRedirect(uploadedPost.postsID)}&gt;{uploadedPost.postsComments} Comment&lt;/button&gt; &lt;button className=&quot;interaction&quot;&gt;Share&lt;/button&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
))}
&lt;/&gt;
}
&lt;/&gt;
}
&lt;/div&gt;
&lt;/div&gt;
&lt;Footer /&gt;
&lt;/&gt;
);
}
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) =&gt; {
const url = process.env.REACT_APP_Backend_URL + &#39;/post/get-like-record&#39;;
await Axios.post (url, {
PostsID : PostID
})
.then ((response) =&gt; {
setLikes(response.data);
if (response.data.length !== 0) {
for (var i = 0; i &lt; response.data.length; i++){
response.data[i].didUserLike = false;
}
const current_state = [...likes];
const current_likes = current_state.find(l =&gt; l.postsLikeAuthor.trim() === loggedInUser);
console.log(current_likes)
if(!current_likes) {
// couldn&#39;t find the post, ID&#39;s dont match
return;
}
// replace the current state to the opposite
current_likes.didUserLike = !current_likes.didUserLike;
setLikes(current_state);
}
})
.catch((error) =&gt; {
setStatusMessage(&quot;Server Side Error&quot;);
});
}

答案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.

huangapple
  • 本文由 发表于 2023年7月11日 00:29:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76655677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定