React 中的“喜欢”和“不喜欢”按钮

问题描述 投票:0回答:1

我想在每篇文章中实现一个喜欢/不喜欢按钮。当我单击“喜欢”时,它会在我的 Rails 后端中更新,并且会从“喜欢”切换到“不喜欢”。然而,当我转到另一个帖子并返回该帖子后,“不喜欢”按钮又回到了“喜欢”。

const [postLikes, setPostLikes] = useState(0);
    const [liked, setLiked] = useState(false);
    const params = useParams();

    useEffect(() => {
        fetch(`/posts/${post.id}/likes`)
        .then(resp => resp.json())
        .then(data => setPostLikes(data))
    }, [post.id])
const handleLike = () => {
        fetch(`/posts/${post.id}/likes`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
        })
        .then(resp => resp.json())
        .then(setLiked(postLikes))
        .catch(error => {
            setErrors(error)
        })
    }

    const handleUnlike = () => {
        fetch(`/posts/${post.id}/likes/${params.id}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            },
        })
        .then(resp => resp.json())
        .then(setLiked(postLikes))
        .catch(error => {
            setErrors(error)
        })
    }
<div className="box-2">
                <h1>{post.title}</h1>
                <h5>{post.creator.username}</h5>
                <p>{post.content}</p>
                {liked ? (
                    <button className="edit-btn" onClick={handleUnlike}>Unlike: {postLikes.length}</button>
                ):(
                    <button className="edit-btn" onClick={handleLike}>like: {postLikes.length}</button>
                )}
                <button className="edit-btn" onClick={openComment}>Comments</button>
                {user && user.username === post.creator?.username && (
                    <>
                    <button className="edit-btn"><Link to={`/posts/${post.id}/edit`}>Edit</Link></button>
                    <button className="edit-btn" onClick={onDeletePost}>Delete</button>
                    </>
                )}
            </div>

我是编码新手,所以这可能是一个简单的解决方案,我只是不知道该怎么做。

reactjs ruby-on-rails react-hooks state togglebutton
1个回答
0
投票

您应该根据获取的点赞数据中是否找到用户的 ID 来更新点赞状态。这可以使用数据数组上的某些方法来完成,以检查用户是否已经喜欢该帖子,如下所示。

const [postLikes, setPostLikes] = useState(0);
const [liked, setLiked] = useState(false);
const params = useParams();

useEffect(() => {
fetch(`/posts/${post.id}/likes`)
.then(resp => resp.json())
.then(data => {
    setPostLikes(data);
    // Check if the user has liked this post
    setLiked(data.some(like => like.user_id === currentUser.id)); 
// Adjust this based on your data structure
})}, [post.id, currentUser.id]);


const handleLike = () => {
fetch(`/posts/${post.id}/likes`, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
})
.then(resp => resp.json())
.then(data => {
    setPostLikes(data);
   // setLiked State to true if response is 200
    setLiked(true);
})
.catch(error => {
    setErrors(error)
});
}

   const handleUnlike = () => {
    fetch(`/posts/${post.id}/likes/${params.id}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
        },
    })
    .then(resp => resp.json())
    .then(data => {
        setPostLikes(data); //setLiked State to false if response is 200
        setLiked(false);
    })
    .catch(error => {
        setErrors(error)
    });
}
 
© www.soinside.com 2019 - 2024. All rights reserved.