【问题标题】:How can get variable value from firebase getDoc() method in react native如何在本机反应中从firebase getDoc()方法获取变量值
【发布时间】:2021-12-01 11:01:08
【问题描述】:

我需要使用来自 firestore 的数据,然后按如下方式通过 getDoc() 检索它们

useEffect(async()=>{
    const docRef = doc(db, "users",user.uid );

    const docSnap = await getDoc(docRef);

    if (docSnap.exists()) {
    
   const  data = docSnap.data();
  const  pic = docSnap.data().photo;
     console.log("data is :", data);
     console.log("pic is :", pic);
   } else {
     // doc.data() will be undefined in this case
     console.log("No such document!");
   }
   })

如下获取数据

data is : Object {
  "age": "25",
  "displayName": "nmar Bot",
  "gender": "male",
  "id": "2wj8dAF9QXYmAWsqKzDSNlyKzzw1",
  "job": "dr",
  "photo": "https://firebasestorage.googleapis.com/v0/b/meet-332208.appspot.com/o/images%2F2wj8dAF9QXYmAWsqKzDSNlyKzzw1%2FprofilePicture.jpeg?alt=media&token=ee74dbd1-26e1-4864-9a9a-c7620d37b902",
  "timestamp": Object {
    "nanoseconds": 920000000,
    "seconds": 1638348589,
  },
}

pic is :"https://firebasestorage.googleapis.com/v0/b/meet-332208.appspot.com/o/images%2F2wj8dAF9QXYmAWsqKzDSNlyKzzw1%2FprofilePicture.jpeg?alt=media&token=ee74dbd1-26e1-4864-9a9a-c7620d37b902"

但是如何在这个中使用这些数据

source = {{uri :pic }}

以及如何调用每个数据显示如下

name is :
age is :
gender is :
photo is :
job is :

有人可以帮我吗?

【问题讨论】:

    标签: javascript firebase react-native google-cloud-firestore


    【解决方案1】:

    由于 Firebase SDK 是基于 Promise 的 API,因此您应该尽可能使用 useAsyncEffect 实现,例如 @react-hook/asyncuse-async-effect。这使您可以修剪大量unnecessary bloat

    注释下面的代码示例以解释每个部分的作用,以及有关特定行作用的任何注释。

    import {useAsyncEffect} from '@react-hook/async'
    
    /* ... */
    
    const [user, userLoading] = useAuth(); // details of this will depend on what AuthContext you use here
    
    // ===================================
    // Getting the data
    // ===================================
    
    const { status, error, value: userData } = useAsyncEffect(async () => {
      if (userLoading) throw new Error("loading"); // user session not validated yet
      if (!user) throw new Error("signed-out"); // not signed in
    
      const docRef = doc(db, "users", user.uid);
    
      return getDoc(docRef)
        .then((snap) => {
          if (!snap.exists()) throw new Error("not-found"); // document missing
          return snap.data();
        });
    }, [user, userLoading]); // rerun when user/userLoading changes
    
    // ===================================
    // Handling different result states
    // ===================================
    
    // if errored, pass the error's code (for
    // firebase errors) or message (for other
    // errors) to the switch instead so you
    // can handle them by simply adding a
    // case to it.
    switch (status === "error" ? error.code || error.message : status) { 
      case "loading":
        return null; // hides component
      case "cancelled":
        /* handle cancelled */
        return (<div class="error">Operation cancelled</div>)
      case "not-signed-in":
        /* handle not signed in */
        return (<div class="error">Not signed in</div>)
      case "not-found":
        /* handle document not found */
        return (<div class="error">Profile data not found</div>)
      default:
        /* handle other errors */
        return (
          <div class="error">
            Failed to retrieve data: {error.code || error.message}
          </div>
        );
      case "success":
        // continues below outside switch
    }
    
    // ===================================
    // Rendering out the completed content
    // ===================================
    
    // Here, userData is your document's data and
    // you could also use a deconstruction pattern
    // to split it up rather than reference it like
    // I have:
    // const { name, age, gender, pic, job } = userData;
    
    return (<>
      <img src={userData.pic} />
      <p>Name: {userData.name}</p>
      <p>Age: {userData.age}</p>
      <p>Gender: {userData.gender}</p>
      <p>Photo: <a href={userData.pic}>{userData.pic}</a></p>
      <p>Job: {userData.job}</p>
    </>)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多