我这样从render()
调用一个函数:
<Avatar src={GetUserAvatar(item.createdBy)} />
该函数应将网址返回到用户的照片:
function GetUserAvatar(userId) {
let userAvatar =
"https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png";
db.collection("users")
.doc(userId)
.get()
.then(function(doc) {
userAvatar = doc.data().photoURL;
});
// Still returns original assignment instead of data().photoURL
return userAvatar;
如何获得data().photoURL
才能从函数返回?
答案 0 :(得分:2)
从firestore中获取数据是异步的,因此您需要为状态分配photoURL
并触发api调用,这将在按钮单击时设置值:
const Avatar = () => {
const [imageUrl, setImageUrl] = useState("");
const getUserAvatar = async userId => {
let userAvatar =
"https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png";
db.collection("users")
.doc(userId)
.get()
.then(function(doc) {
setImageUrl(doc.data().photoURL);
});
};
// Assuming you have the user id to pass in
return (
<>
<Avatar src={imageUrl} />
<button onClick={() => getUserAvatar(user.id)}>Get avatar</button>
</>
);
};