![](/img/trans.png)
[英]With a React Hooks' setter, how can I set data before the component renders?
[英]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.