我如何从Firebase存储下载图像并将它们作为Pro分配给React中的文档?

问题描述 投票:0回答:1

我正在开发具有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
}
reactjs firebase hook firebase-storage react-props
1个回答
0
投票

由于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)
    })
  })
© www.soinside.com 2019 - 2024. All rights reserved.