如何在React中显示Firebase存储中的所有图像?

时间:2020-11-06 03:14:21

标签: javascript reactjs firebase firebase-storage

我正在尝试在React应用中显示Firebase存储中的图像。 我可以使用listall从Firebase Storage获取所有图像。 但我不知道如何在ui上显示这些内容。 我尝试使用地图方法,但是没有用。 另外,即使重新加载页面,我也要保留这些显示。 我应该使用localstrage还是useEffect?

请帮助我。 这是我的代码。

const PhotoButton = () => {


    var storageRef = firebase.storage().ref("images");
  
    const [image, setImage] = useState("");
    const [imageUrl, setImageUrl] = useState([]);
    const handleImage = event => {
        const image = event.target.files[0];
        setImage(image);
    };

    const onSubmit = event => {
        event.preventDefault();
        if (image === "") {
          console.log(“error);
          return;
        }
      
        const uploadTask = storage.ref(`/images/${image.name}`).put(image);
        uploadTask.on(
          firebase.storage.TaskEvent.STATE_CHANGED,
          next,
          error,
          complete
        );
    };

    const complete = () => {
        storage
          .ref("images")
          .child(image.name)
          .getDownloadURL()
          .then(fireBaseUrl => {
            setImageUrl(fireBaseUrl);
          });
    };

    // Now we get the references of these images
    storageRef.listAll().then(function(result) {
        result.items.forEach(function(imageRef) {
        // And finally display them
        console.log(result.items);
        displayImage(imageRef);
        });
    }).catch(function(error) {
        alert(“error!”)
    });
  
    function displayImage(imageRef) {
        imageRef.getDownloadURL().then(function(url) {
            setImageUrl.push(url);
        // TODO: Display the image on the UI
        }).catch(function(error) {
        // Handle any errors
        });
    }
   
    return(
        <div>
            <h3 className={classes.addPhotoText}>Photos</h3>
            <div className="addphoto">
            <form onSubmit={onSubmit}>
                <input type="file" onChange={handleImage} />
                <Button type="submit" className={classes.PhotoButton}>Submit</Button>
            </form>
            </div>
            <img src={imageUrl} />

            {imageUrl.map((url) => (
                <img src={url}/>
            ))}
        </div>
    );

}

export default PhotoButton

2 个答案:

答案 0 :(得分:1)

它与此代码配合使用。

useEffect(() => {
    const fetchImages = async () => {

    let result = await storageRef.child('images').listAll();
        let urlPromises = result.items.map(imageRef => imageRef.getDownloadURL());
    
        return Promise.all(urlPromises);

    }
    
    const loadImages = async () => {
        const urls = await fetchImages();
        setFiles(urls);
    }
    loadImages();
    }, []);

答案 1 :(得分:1)

对我来说,我需要在@via 答案中添加一些内容才能使其正常工作。我箍它可以帮助别人

Firebase 配置

import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/storage";
import "firebase/auth";

const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: "",
};

if (firebase.apps.length === 0) {
  firebase.initializeApp(firebaseConfig);
}

const auth = firebase.auth();
const db = firebase.firestore();
const storage = firebase.storage();

export { db, storage, auth };

代码

import { storage } from "../components/config/config";

 // Get all the images from Storage
    const [files, setFiles] = useState();

useEffect(() => {
    const fetchImages = async () => {
      let result = await storage.ref().child("Name Of Your Files Map in storage").listAll();
      let urlPromises = result.items.map((imageRef) =>
        imageRef.getDownloadURL()
      );

      return Promise.all(urlPromises);
    };

    const loadImages = async () => {
      const urls = await fetchImages();
      setFiles(urls);
    };
    loadImages();
}, []);

  console.log(files);