繁体   English   中英

无法显示来自 firebase firestore 和反应 js 的图像

[英]Can not display Image from firebase firestore and react js

我有一个从firestore获取数据库的应用程序,并且图像保存在firestorage上,我的应用程序工作得很好,但是图像显示为未定义,经过大量不同的试验后,我注意到图像加载了,然后有东西将其清除,不确定我的代码中缺少什么。

从 Firestore 和 Firestorage 检索数据的代码

  useEffect(() => {
    const getList = async () => {
      const data = await getDocs(query(edu_Collection, orderBy('date', 'desc')))
      setEducationList(
        data.docs.map(doc  =>
        {
          let data = {
            id: doc.id, 
            name: doc.data().name, 
            location: doc.data().location, 
            image: doc.data().image, 
            date: doc.data().date.toDate()
          } as Education;
          
          const reference = ref(storage, data.image)
          getDownloadURL(reference)
          .then(url => { data.fullPath = url; setLoaded(true); console.log(url) })
          .catch(err => console.error(err))

          
          return data
        })
      )
    }
    getList()

  }, [])

渲染部分

    <Row>
      {educationList.map((item: Education) => (
        <Col key={item.id} xs={4}>
          <Card>
          <div className={styles.CardImageContainer}>
            <Card.Img 
              className={styles.CardImage} 
              variant="top" 
              src={item.fullPath} />
          </div>
          <Card.Body>
            <Card.Title>{item.name}</Card.Title>
            <Card.Text>
              {item.location}
            </Card.Text>
            <CustomDate date={item.date} />
          </Card.Body>
          </Card>
        </Col>
      ))}
    </Row>

问题可能是因为您混淆了 promise 和异步等待的方式。 请尝试我的解决方案

  useEffect(() => {
    const getList = async () => {
      const data = await getDocs(query(edu_Collection, orderBy('date', 'desc')));
      const educations = [];

      for (let index = 0; index < data.docs.length; index++) {
        const doc = data.docs[index];
        let data = {
          id: doc.id, 
          name: doc.data().name, 
          location: doc.data().location, 
          image: doc.data().image, 
          date: doc.data().date.toDate()
        } as Education;

        const reference = ref(storage, data.image);
        data.fullPath =await getDownloadURL(reference);

        educations.push(data);
      }

      setEducationList(educations);
    };

    getList()
  }, [])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM