【问题标题】:Deleting the document from Firebase with unique id从具有唯一 ID 的 Firebase 中删除文档
【发布时间】:2021-06-23 08:48:13
【问题描述】:

下面是useEffect和向firebase添加评论(文档)的函数

const postComment = (event) => {        
            event.preventDefault()
            db.collection("posts").doc(postId).collection("comments").add({
            caption: comment,
            header: signInUser.displayName,
            timestamp: firebase.firestore.FieldValue.serverTimestamp()
        });
        setComment('');
    }
    useEffect(() => {
        let unsubscribe;
        if(postId){
            unsubscribe = db
            .collection("posts")
            .doc(postId)
            .collection('comments')
            .orderBy('timestamp', 'asc')
            .onSnapshot((snapshot)=>{
                setComments(snapshot.docs.map((doc) =>{
                    return{
                    commentIdTest : doc.id,
                    commentTest: doc.data()
                    }}
                ));
            });
        }
        return () => {
            unsubscribe();
        }
    }, [postId]);

下面是我通过评论列表映射的反应返回函数

{comments.map((comment)=>(
                
                <div className="Post__commentIcon">
                    <p>
                        <b>{comment.commentTest.header}</b> {comment.commentTest.caption} 
                    </p>
                    <div className="post__DeletePost"><Button onClick={deletingComment}><strong>X</strong></Button></div>
                </div>
            ))} 

我想在点击我上面所做的按钮时从firebase中删除评论,删除评论的功能如下**

const deletingComment =(e, commentIdTest) =>{
        e.stopPropagation();
        db.collection("posts").doc(postId).collection('comments').orderBy('timestamp').get()
         .then((querySnapshot)=>{
            querySnapshot.forEach(function (doc){
                 doc.ref.delete();
            })
         });
    }

当我只想删除被点击的评论时,它会删除整个集合。

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore


    【解决方案1】:

    您需要指定要删除的评论的id,并将代码更改为如下内容:

    const deletingComment = (e, commentId) => {
      e.stopPropagation();
      db.collection("posts")
        .doc(postId)
        .collection("comments")
        .doc(commentId)
        .delete();
    };
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      相关资源
      最近更新 更多