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

Firestore React追加数据时报TypeError: is not iterable错误求助

问题解决:TypeError: OriginalContent is not iterable

错误原因

你的OriginalContent是Firestore返回的对象(结构为{uid1:"a", uid2:"b"}),而数组扩展运算符[...xxx]只能用于可迭代对象(比如数组),直接对对象使用会抛出"not iterable"错误。

正确解决方案

因为你要给原对象新增键值对,应该用对象扩展运算符合并对象,而不是数组的方式:

const OriginalContentSnap = await getDoc(doc(db, "Comment", curSnap.id));
// 处理文档不存在的情况,避免data()返回null导致后续报错
const OriginalContent = OriginalContentSnap.data() || {};
const CommentContent = {[uid]: commentDocID.id};
// 合并原对象与新内容,新键会自动添加
const updatedContent = {...OriginalContent, ...CommentContent};
// 更新数据库,merge: true确保只更新新增/修改的字段,不覆盖整个文档
await setDoc(doc(db, "Comment", curSnap.id), updatedContent, { merge: true });

可选:如果需要数组结构的评论

如果后续需要有序的评论列表,可以将Comment文档结构改为数组格式,比如:

Comment: {
  comments: [
    {uid: "uid1", content: "a"},
    {uid: "uid2", content: "b"}
  ]
}

对应的更新代码就可以用数组扩展运算符:

const OriginalContentSnap = await getDoc(doc(db, "Comment", curSnap.id));
const OriginalContent = OriginalContentSnap.data() || { comments: [] };
const newComment = {uid: uid, content: commentDocID.id};
const updatedComments = [...OriginalContent.comments, newComment];
await setDoc(doc(db, "Comment", curSnap.id), { comments: updatedComments }, { merge: true });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:05:27