reactjs React:“为什么上传的图片和信息在重新加载页面后消失了?”

pgvzfuti  于 2023-02-22  发布在  React
关注(0)|答案(1)|浏览(237)

React我是一个初学者,我正在做一个Web应用程序,可以上传照片,还可以预览照片
我希望这段代码可以上传照片,照片会存储在Firebase Storage中,而照片信息也会存储在Firebase数据库中,照片和照片信息可以显示在网页上,当我右键点击并按删除时,照片也会被删除,当页面重新加载时,没有被删除的照片和信息仍然会显示。
但是当我完成这段代码的时候,我发现照片可以存储在Firebase存储器中,照片信息也存储在Firebase数据库中,并且两者都显示在页面上,但是当我重新加载页面的时候,所有的都消失了。我发现它很长一段时间都不知道在哪里了,所以我想问一下大家,谢谢大家!
我希望能够上传图片并显示在页面上。同时,图片将存储在fireStorage中,照片信息将存储在firebase数据库中。当我点击右键时,它将显示删除按钮,按下删除按钮后,图片将直接消失。当页面重新加载时,页面将显示未删除的照片。

import { useState, useEffect } from "react";
 import {
  ref,
  uploadBytes,
  getDownloadURL,
  listAll,
  deleteObject,
} from "firebase/storage";
 import { db, storage } from "../utils/firebase";
 import {
  addDoc,
  collection,
  Timestamp,
  query,
  where,
  deleteDoc,
  getDocs,
} from "firebase/firestore";
 import { Image, Dropdown, Input } from "antd";
 import { AppstoreAddOutlined } from "@ant-design/icons";
 import { nanoid } from "nanoid";

 const items = [
  {
    label: "移除",
    key: "1",
  },
];

function UploadButton() {
  const [deleteImageRef, setImageUrls] = useState([]);
  const [originalImageUrls, setOriginalImageUrls] = useState([]);

  const handleImageUpload = (event) => {
    const imageUpload = event.target.files[0];
    if (imageUpload == null) return;
    const imageRef = ref(storage, `images/${imageUpload.name}`);
    uploadBytes(imageRef, imageUpload).then((snapshot) => {
      getDownloadURL(snapshot.ref).then((url) => {
        const file = {
          id: nanoid(),
          name: `${imageUpload.name}`,
          size: `${imageUpload.size}`,
          type: `${imageUpload.type}`,
          url: url,
          timestamp: Timestamp.now(),
        };
        setImageUrls((prev) => [...prev, file]);
        setOriginalImageUrls((prev) => [...prev, file]);
        const galleryCollectionRef = collection(db, "gallery");
        addDoc(galleryCollectionRef, file)
          .then(() => {
            console.log("File info added to Firestore");
          })
          .catch((error) => {
            console.error("Error adding file:", error);
          });
      });
    });
  };

  const deleteImage = async (url) => {
    console.log({ url });
    const galleryCollectionRef = collection(db, "gallery");
    const querySnapshot = await getDocs(
      query(galleryCollectionRef, where("url", "==", url))
    );
    querySnapshot.forEach(async (doc) => {
      await deleteDoc(doc.ref);
    });
    const imageRef = ref(storage, url);
    await deleteObject(imageRef);
    setImageUrls((prev) => prev.filter((image) => image.url !== url));
    setOriginalImageUrls((prev) => prev.filter((image) => image.url !== url));
  };

  useEffect(() => {
    const imagesListRef = ref(storage, `images/`);
    listAll(imagesListRef)
      .then((response) => Promise.all(response.items.map(getDownloadURL)))
      .then((url) => {
        setImageUrls(url);
        setOriginalImageUrls(url);
      })
      .catch((error) => console.log(error));
  }, []);

  const handleSearch = (value) => {
    if (value === "") {
      setImageUrls(originalImageUrls);
    } else {
      const filteredUrls = originalImageUrls.filter((url) =>
        url.toLowerCase().includes(value.toLowerCase())
      );
      setImageUrls(filteredUrls);
    }
  };

  return (
    <div className="upload-container">
      <div className="img-container-gallery">
        <Image.PreviewGroup className="upload-img">
          {deleteImageRef.map((image, index) => (
            <Dropdown
              menu={{
                items,
                onClick: async ({ key }) => {
                  if (key === "1") {
                    await deleteImage(image.url);
                  }
                },
              }}
              trigger={["contextMenu"]}
              key={index}
            >
              <span>
                <Image width={200} src={image.url} />
                <div>
                  <p>Name:{image.name}</p>
                </div>
              </span>
            </Dropdown>
          ))}
        </Image.PreviewGroup>
      </div>
      <div className="bottom-container">
        <div className="search-container">
          <Input.Search
            placeholder="Input text..."
            allowClear
            size="small"
            onSearch={handleSearch}
            onPressEnter={(e) => handleSearch(e.target.value)}
            onChange={(e) => {
              e.target.value && setImageUrls(originalImageUrls);
            }}
            className="search-input"
          />
        </div>
        <div className="button-container">
          <label
            htmlfor="file-upload"
            className="custom-upload-btn"
            onChange={handleImageUpload}
          >
            Upload Image
            <input type="file" id="file-upload" />
          </label>
          <div className="sort-btn-container">
            <button className="sort-btn">
              <AppstoreAddOutlined />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
export default UploadButton;
i7uaboj4

i7uaboj41#

在你的useEffect中,你应该从API中获取所有的照片,然后将它们设置为状态
您可以将此状态Map到图像标签以显示照片。如果您在重新加载时看不到图像,则说明您没有正确获取和/或设置图像。
检查这部分代码:

useEffect(() => {
    const imagesListRef = ref(storage, `images/`);
    listAll(imagesListRef)
      .then((response) => Promise.all(response.items.map(getDownloadURL)))
      .then((url) => {
        setImageUrls(url);
        setOriginalImageUrls(url);
      })
      .catch((error) => console.log(error));
  }, []);

添加控制台日志并查看是否正确获取和设置映像

相关问题