如何在React中显示Firebase存储中的所有图像? [英] How to display all the images from firebase storage in React?
本文介绍了如何在React中显示Firebase存储中的所有图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在我的React应用程序中显示Firebase存储中的图像.我可以使用listall从Firebase Storage获取所有图像.但我不知道如何在ui上显示这些内容.我尝试使用地图方法,但是没有用.另外,即使重新加载页面,我也要保持这些显示.我应该使用localstrage还是useEffect?
I am trying to display images from Firebase storage in my React app. I could get all images from Firebase Storage using by listall. but I don't know how to display these on ui. I tried to use map method but didn't work. Also, I want to keep these display even if page is reload. should I use localstrage or useEffect?
请帮助我.这是我的代码.
plz help me. here is my code.
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
推荐答案
此代码适用.
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();
}, []);
这篇关于如何在React中显示Firebase存储中的所有图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文