【发布时间】:2018-07-30 06:06:24
【问题描述】:
我有已上传到 Firebase 存储的图像,我想再次下载它们以在组件中呈现它们。我在 Firebase 实时数据库中保存了一个名称列表,以便我可以使用这些名称从 Firebase 存储中检索图像。
在 componentDidMount 中,我正在检索图像,然后将它们作为数组保存到 this.state。当我尝试在我的渲染函数中映射数组时,什么也没有发生。如果我 console.log(this.state.images) 我看到了数组,但我不能映射它来渲染它。
export default class Images extends Component {
constructor(props) {
super(props);
this.state = store.getState();
}
componentDidMount() {
this.unsubscribe = store.subscribe(() => {
this.setState(store.getState());
});
let photos = [];
database
.ref("images/")
.once("value")
.then(function(snapshot) {
let values = snapshot.val();
let images = [];
for (var key in values) {
images.push(values[key]["filename"]);
}
images.map(image => {
// Create a reference to the file we want to download
const storageRef = storage.ref();
// Get the download URL
storageRef
.child("images/" + image)
.getDownloadURL()
.then(function(url) {
// Insert url into an <img> tag to "download"
photos.push(url);
})
.catch(function(error) {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case "storage/object_not_found":
// File doesn't exist
break;
case "storage/unauthorized":
// User doesn't have permission to access the object
break;
case "storage/canceled":
// User canceled the upload
break;
case "storage/unknown":
// Unknown error occurred, inspect the server
break;
}
});
});
});
this.setState({ images: photos})
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
return (
<div>
{this.state.images && this.state.images.map(image => {
console.log(image)
})
}
</div>
)
}
}
【问题讨论】:
-
我能够通过添加一个按钮来显示所有图像并使用使用 forceUpdate() 方法重新渲染页面的 handleClick 函数来解决这个问题。
标签: reactjs firebase firebase-realtime-database firebase-storage