在我可以设置图像的 src 之前反应组件渲染

React component renders before I can set src of image

我有这个应用程序可以刷出一系列卡片。有些人对文字有疑问。显然没有问题。但图像源正在从 firebase 中检索。在每个渲染上,我检查它是否有文本或图像问题,如果它有图像,我会在数据库中查询 downloadURL 并将其作为源插入。如果我将它硬编码插入,它工作正常,如果我控制台记录响应,它是准确的。我的问题是我相信组件在我可以动态插入源之前呈现。代码如下。是的,我知道有那么多条件语句,它看起来像一棵圣诞树,可能真的是不好的做法。 为了节省一些阅读时间,我将在此处提出请求的地方拼接它...

useEffect(() => {
    if ("imageHolder" in active) {
      const asyncFunc = async () => {
        setLoading(true);
        setImage(true);
        await storageRef
          .child(active.imageHolder)
          .getDownloadURL()
          .then(function (url) {
            imageSrc = url;
            console.log("url returns ", url);
          })
          .catch(function (error) {
            console.log(error);
          });
      };
      asyncFunc();
      setLoading(false);
    }
  }, [active, getQuestions, correctAnswer]);

我在这里插入它的地方

 ) : image ? (
          loading ? (
            <h1>Loading</h1>
          ) : (
            <img alt="" src={imageSrc} className="d-inline-block align-top" />
          )
        ) : (
          <h3>{active.question}</h3>
        )}
      </div>
      <div className="answerGrid">
        {loading ? (

非常感谢您的任何建议。保持健康!

我认为对此的简单决定是在 src 中添加一个合乎逻辑的 "or" 运算符 像这样

<img alt="" src={imageSrc || ''} className="d-inline-block align-top" />

查看其余代码可能会有所帮助,但鉴于提供的代码片段,我假设问题出在 imageSrc 变量的设置方式上。

您是否尝试过管理 imageSrc 作为状态?例如

const [imageSrc, setImageSrc] = useState('')

// then use setImageSrc after getting the url
await storageRef
          .child(active.imageHolder)
          .getDownloadURL()
          .then(function (url) {
            setImageSrc(url)
            console.log("url returns ", url);
          })