我正在开发具有Firestore数据库的React Web应用程序,并尝试使用StorageRef和getDownloadURL()从Firebase存储下载多个图像。我想将图像URL分配为doc的道具,但不起作用。有人知道我在做什么错吗?
function useDishes() {
const [dishes, setDishes] = useState([])
useEffect(() => {
firebase
.firestore()
.collection('dishes')
.onSnapshot(snapshot => {
const storage = firebase.storage()
const storageRef = storage.ref()
const newDish = snapshot.docs.map(doc => ({
id: doc.id,
...doc.data(),
getDownloadURLs: storageRef
.child(doc.data().imageString)
.getDownloadURL()
.then(url => {
console.log(url)
console.log(doc.data())
//assign url as prop to doc
return url
}),
}))
setDishes(newDish)
})
}, [])
return dishes
}
由于getDownloadURL
也是一个异步调用,因此您需要在其回调中调用setDishes
。
firebase
.firestore()
.collection('dishes')
.onSnapshot(snapshot => {
const storage = firebase.storage()
const storageRef = storage.ref()
const promises = snapshot.docs.map(doc => storageRef.child(doc.data().imageString).getDownloadURL());
Promise.all(promises).then(downloadURLs => {
const newDish = snapshot.docs.map((doc, index) => ({
id: doc.id,
...doc.data(),
getDownloadURLs: downloadURLs[index]
}))
setDishes(newDish)
})
})