将用户属性分配给firebase中的变量并做出反应

时间:2019-11-27 19:09:20

标签: reactjs google-cloud-firestore

我这样从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才能从函数返回?

1 个答案:

答案 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>
    </>
  );
};