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

如何在Firebase数据库中获取Post ID以实现帖子点赞切换功能?

解决点赞按钮无法获取Post ID的问题

你的toggleLike函数逻辑是正常的,核心问题是要把对应帖子的ID正确传递到函数里,以下是几种常见场景的解决方法:

场景1:帖子列表循环渲染(如Vue/React等框架)

如果是在列表里渲染多个帖子,直接在点击事件中绑定当前帖子的ID即可:

<!-- Vue示例 -->
<div v-for="post in posts" :key="post.id">
  <!-- 帖子内容区域 -->
  <button @click="toggleLike(post.id)">
    {{ post.likes || 0 }} 赞
  </button>
</div>
// React示例
posts.map(post => (
  <div key={post.id}>
    {/* 帖子内容区域 */}
    <button onClick={() => toggleLike(post.id)}>
      {post.likes || 0} 赞
    </button>
  </div>
))

场景2:单个帖子详情页

如果是在详情页,可从路由参数或组件props中获取Post ID:

// Vue路由示例
const postId = this.$route.params.postId;
toggleLike(postId);

// React路由示例(react-router-dom)
const { postId } = useParams();
toggleLike(postId);

场景3:原生JavaScript场景

给点赞按钮添加自定义属性存储Post ID,点击时读取:

<button class="like-btn" data-post-id="your-post-id">点赞</button>
document.querySelectorAll('.like-btn').forEach(btn => {
  btn.addEventListener('click', function() {
    const postId = this.dataset.postId;
    toggleLike(postId);
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 07:07:22