簡體   English   中英

如何從 Firebase 雲存儲中刪除圖像 - 反應

[英]How to Delete Image from Firebase cloud Storage - REACT

我的Storage中有以下結構 Post/ID/image.jpg。 Post 和 ID 是可以輕松找到的文件夾,但 ID 可能包含多個圖像。 我怎么可能刪除所有這些? 在我的代碼中,我有一個 function 應該刪除 Firestore firestore database中的帖子並從firebase storage中刪除圖像引用

拋出的錯誤是:

TypeError:無法讀取未定義的屬性(讀取“_throwIfRoot”)

刪除 Function

const DeletePost = async (e) => {
    e.preventDefault();
    const querySnapshot = await getDocs(collection(db, `${category}Posts`));
    querySnapshot.forEach((docx) => {
        if (post.AdTitle === docx.data().AdTitle) {
            try {
                deleteObject(ref(storage, `${category}Posts`, docx.id).child);
                deleteDoc(doc(db, `${category}Posts`, docx.id));
            } catch (error) {
                console.log("error in delete image, " + error);
            }
            // router.reload();
        }
    });
};

編輯

郵件文件夾 要刪除的圖像 Docx.id 的內容

StorageReference上沒有child屬性。 嘗試刪除它,如下所示:

deleteObject(ref(storage, `${category}Posts`, docx.id + ".ext")) // .child);

// Make sure you add the file extension at the end

此外, deleteObject()deleteDoc都返回 promise,因此請檢查: Using async/await with a forEach loop

按照這個文檔,我終於想出了一個可行的解決方案,這是更新的代碼。

try {
    const listRef = ref(storage, `${category}Posts/${docx.id}/`);
    listAll(listRef)
      .then((res) => {
        res.items.forEach((itemRef) => {
          setValues((prevState) => [...prevState, itemRef]);
        });
        if (values !== "") {
          console.log("attempting");
          values?.map((value) =>
            deleteObject(
              ref(storage, `${category}Posts/${docx.id}/${value.name}`)
            ).then(() => {
              console.log("storage success");
            })
          );

          deleteDoc(doc(db, `${category}Posts`, docx.id)).then(() => {
            console.log("doc success");
            router.reload();
          });
        }
      })
      .catch((error) => {
        console.log("error : " + error);
      })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM