You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React前端点赞计数器实时更新问题(API功能正常)

Fixing Real-Time Like Count Updates in Your React Component

Hey there! Let's get that like count updating without needing a page refresh—super common issue when working with state and API calls in React.

The Problem

Right now, you're rendering the like count directly from the post prop your component receives. When you call addLike, the backend updates the like data, but your component has no way of knowing to re-render with the new value because the prop itself doesn't change (unless the parent component fetches the updated post again).

The Solution

We need to store the post data in a local component state so we can update it immediately after the like is added, triggering a re-render and showing the new count right away. Here's how to adjust your code:

import "./Post.css";
import { useState } from "react";
import { addLike } from '../../lib/social-network-library-master';

function Post({ post: initialPost }) {
  // Initialize local state with the incoming post prop
  const [currentPost, setCurrentPost] = useState(initialPost);

  const handleLikes = async () => {
    try {
      // Call addLike—assuming this function returns the UPDATED post object
      const updatedPost = await addLike(currentPost._id);
      // Update local state to trigger re-render with new like count
      setCurrentPost(updatedPost);
    } catch (error) {
      // Always good to handle errors so you know if something goes wrong
      console.error("Oops, couldn't add that like:", error);
    }
  };

  return (
    <div id="general-container">
      <h2>{currentPost.title}</h2><br/>
      <p>{currentPost.content}</p><br/>
      <p>Posté par {currentPost.firstname} {currentPost.lastname}</p><br/>
      <div className="boutton-like-container">
        {/* Simplified onClick since handleLikes doesn't need extra params */}
        <button className="boutton-like" onClick={handleLikes}>
          like
        </button>
        <p>{currentPost.likes.length} likes</p>
      </div>
    </div>
  )
};

export default Post;

What If addLike Doesn't Return the Updated Post?

If your addLike API call only returns a success status (not the full updated post), you can manually update the like count in state instead:

const handleLikes = async () => {
  try {
    await addLike(currentPost._id);
    // Manually increment the like count by adding a placeholder like object
    setCurrentPost(prevPost => ({
      ...prevPost,
      likes: [...prevPost.likes, {}] // Replace {} with actual like data if you have it
    }));
  } catch (error) {
    console.error("Failed to add like:", error);
  }
};

Bonus Tip

If this Post component is part of a list of posts, you might want to update the post data in the parent component's state too (so other instances or the list view stay in sync). But for a single post component, the local state fix above will work perfectly.

内容的提问来源于stack exchange,提问作者Stilgaar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 14:13:16