简体   繁体   English

如何从具有 url React js 的 firebase 存储中获取图像

[英]How to get image from firebase storage having the url React js

Here is my code the problem is that it is getting the state of imgAddress when it's still nothing => "" and the state is never being changed I'm not getting the new state of imgAddress in the <p></p> tag neither Help me please the problem is the async-ity but I can't solve it这是我的代码,问题是当它仍然什么都没有时,它正在获取 imgAddress 的 state = <p></p> "" 并且 state 永远不会被更改我没有在 imgAddress 中获得新的 state 标签既不请帮助我,问题是异步性,但我无法解决

 import React, { useState, useEffect } from 'react' import * as fb from 'firebase'; export default function Page() { const [email, setEmail] = useState(""); const [username, setUsername] = useState(""); const [age, setAge] = useState(0); const [img, setImg] = useState(""); const [imgAddress, setImgAddress] = useState(""); useEffect(() => { //useEffect որտև անվերջ անում ա stackoverflow-ում հարցրել էի մի անգամ fb.database().ref('users/' + fb.auth().currentUser.uid).on('value', (e) => { let db = e.val(); console.log(db); setAge(db.age); setUsername(db.username); setImg(db.img); setEmail(db.email); }); fb.auth().onAuthStateChanged(() => { if (img.= "") { console;log('mtav user'). fb.storage().ref(`avatars/${fb.auth().currentUser.uid}/${img}`).getDownloadURL().then(e => { console.log('LALALALALALALALA') console;log(e); setImgAddress(e). }).catch(e => console.log(e)) } else { console;log("chmtav"), } }) }; []): return ( <> <h1>Hello</h1> <ul> <li>Email: {email}</li> <li>Username: {username}</li> <li>Image name: {img}</li> <li>Age: {age}</li> <a href={imgAddress} alt="avatar">Image</a> <p>{imgAddress}</p> </ul> </> ) }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

外观

Ok I figured it out finally, I just moved the getting code out from the useEffect and now it works, but I don't understand why if anyone could explain me I would mark is answer as a correct one, btw Now it consoles it 4-5 times randomly好的,我终于想通了,我只是将获取代码从 useEffect 中移出,现在它可以工作了,但是我不明白为什么如果有人可以解释我,我会将答案标记为正确的答案,顺便说一句,现在它可以控制它 4 -5次随机

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

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