簡體   English   中英

在我可以設置圖像的 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 中添加一個邏輯“或”運算符

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

查看代碼的 rest 可能會有所幫助,但鑒於提供的片段,我假設問題在於imageSrc變量的設置方式。

您是否嘗試將imageSrc管理為 state? 例如

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);
          })


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM