我在Firebase / Storage上创建了一个文件夹。该文件夹(/测试)包含多个图像。
我想在我的React组件中显示/ test文件夹中的所有图像,而不必命名它们。
我是React的初学者。
到目前为止,我所要做的就是通过给出他的名字来显示单个图像。我将代码放在下面。
感谢您的帮助!
import React from "react";
import firebaseApp from "../Firebase";
class DisplayImage extends React.Component {
constructor() {
super();
this.state = {
mypicture: ""
};
this.getImage("mypicture");
}
getImage(image) {
let { state } = this;
firebaseApp
.storage()
.ref()
.child("/test")
.child(`${image}.jpg`)
.getDownloadURL()
.then(url => {
state[image] = url;
this.setState(state);
})
.catch(error => {
// Handle any errors
});
}
render() {
return (
<div>
<img src={this.state.mypicture} alt="Lithuanian flag" />
</div>
);
}
}
export default DisplayImage;
编辑
这是更新的代码。我无法显示/ test文件夹中的图像。这是因为渲染部分
import React from "react";
import firebaseApp from "../Firebase";
class DisplayImage extends React.Component {
constructor() {
super();
this.state = {
images: []
};
this.getImage("images");
}
getImage() {
let { state } = this;
// Create a reference under which you want to list
var listRef = firebaseApp
.storage()
.ref()
.child("/test");
// Find all the prefixes and items.
listRef
.listAll()
.then(function(res) {
// Store the list in the state, just in case we need it somewhere
state.images = res.items;
state.downloadURLs = {}; // in here we'll store the download URL for each image by its name
this.setState(state);
res.items.forEach(function(itemRef) {
itemRef
.getDownloadURL()
.then(url => {
// state.downloadURLs[itemRef.name] = url;
state.downloadURLs.push(url);
this.setState(state);
})
.catch(error => {
// Handle any errors
});
});
})
.catch(function(error) {
// Uh-oh, an error occurred!
});
}
render() {
let images = this.state.images;
return (
<div>
<ul>
{Object.keys(images).map((image, index) => (
<li key={index}>
{image} : {images[image]}
</li>
))}
</ul>
</div>
);
}
}
export default DisplayImage;
但是,我确实在状态中看到了两个图像(从/ test文件夹中)
Firebase Storage SDK的某个位置具有lists the files的API。将其与您当前的代码结合起来,您可以通过下载URL显示文件夹中的所有文件,例如:
// Create a reference under which you want to list
var listRef = firebaseApp.storage().ref().child('/test');
// Find all the prefixes and items.
listRef.listAll().then(function(res) {
// Store the list in the state, just in case we need it somewhere
state.images = res.items;
state.downloadURLs = {}; // in here we'll store the download URL for each image by its name
this.setState(state);
res.items.forEach(function(itemRef) {
itemRef.getDownloadURL()
.then(url => {
state.downloadURLs[itemRef.name] = url;
this.setState(state);
})
.catch(error => {
// Handle any errors
});
});
}).catch(function(error) {
// Uh-oh, an error occurred!
});
以上内容将下载URL存储在对象中,其名称为它们所属的图像的名称。因此,例如:
images = ["/test/art.jpg", "/test/banana.jpg"];
downloadURLs = {
"art.jpg": "download URL to image",
"banana.jpg": "download URL to image",
};
这使您可以按照列表调用中返回图像的顺序来处理图像。如果您只需要下载URL,则可以将它们存储在一个数组中:
state.downloadURLs = [];
...
state.downloadURLs.push(url);