[英]React component renders before I can set src of image
I have this application that flashes a series of cards.我有一个闪烁一系列卡片的应用程序。 Some have questions with text.
有些人对文字有疑问。 No problem there obviously.
那里显然没有问题。 But the image source is being retrieved from firebase.
但是图像源是从 firebase 中检索的。 On each render I check if it has a question with text, or with an image and if it has an image I query the database for the downloadURL and insert that as the source.
在每次渲染时,我都会检查它是否有关于文本或图像的问题,如果它有图像,我会在数据库中查询 downloadURL 并将其作为源插入。 If I insert it hard coded it works fine, if I console log the response it's accurate.
如果我将它硬编码插入它工作正常,如果我控制台记录响应它是准确的。 My problem is I believe that the component renders before I can insert the source dynamically.
我的问题是我相信组件在我可以动态插入源之前呈现。 Code is below.
代码如下。 And yes, I know with that many conditionals it looks like a christmas tree and is probably really bad practice.
是的,我知道有这么多条件,它看起来像一棵圣诞树,可能是非常糟糕的做法。 To save some reading I'll splice it where I make the request here...
为了节省一些阅读量,我将在此处提出请求的地方拼接它...
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]);
And where I insert it here我在这里插入它
) : image ? (
loading ? (
<h1>Loading</h1>
) : (
<img alt="" src={imageSrc} className="d-inline-block align-top" />
)
) : (
<h3>{active.question}</h3>
)}
</div>
<div className="answerGrid">
{loading ? (
Thanks for any advice at all.非常感谢您的任何建议。 And stay healthy!
并保持健康!
I think simple decision to this will be adding a logical "or" operator in src like this我认为对此的简单决定将是像这样在 src 中添加一个逻辑“或”运算符
<img alt="" src={imageSrc || ''} className="d-inline-block align-top" />
It might be helpful to see the rest of the code, but given the provided snippets, I'm assuming the problem is with how the imageSrc
variable is getting set.查看代码的 rest 可能会有所帮助,但鉴于提供的片段,我假设问题在于
imageSrc
变量的设置方式。
Have you tried managing the imageSrc
as state?您是否尝试将
imageSrc
管理为 state? Eg例如
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.