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

Firestore关联指定文档ID创建子集合时自动生成新文档问题求助

问题根因

你遇到的问题是两处错误叠加导致的:

  1. React的key是框架内部保留的特殊属性,无法在组件内部通过props读取,你Post组件里拿到的key永远是undefined
  2. Feed组件中你取错了帖子的Firestore文档ID,真实ID存在post.id,而不是你用的post.data.id

当你调用db.collection('posts').doc(undefined)时,Firestore会判定你需要新建一个posts文档,自动生成随机ID,所以才会出现每次提交评论都新建帖子文档的问题。


修复步骤

1. 修改Feed组件的传参

给Post组件新增postId属性传递真实的Firestore文档ID,同时修正key的取值:

{posts.map(post => (
  <Post
    key={post.id}
    postId={post.id}
    profilePic={post.data.profilePic}
    message={post.data.message}
    timestamp={post.data.timestamp}
    username={post.data.username}
    image={post.data.image}
  />
))}

2. 修改Post组件的逻辑

首先修改props接收,把key换成postId:

function Post({postId, profilePic, image, username, timestamp, message}) {

然后修改sendComment方法里的文档定位逻辑,用postId代替原来的key:

await db.collection('posts').doc(postId)
.collection('comments').add ({
  comment: commentToSend,
  profilePic: user.photoURL,
  username: user.displayName,
  timestamp: firebase.firestore.FieldValue.serverTimestamp(),
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:36:08