簡體   English   中英

為什么 firebase 在我的組件中返回 undefined 但我在讀取數據庫時可以在 console.log 中看到 object?

[英]Why does firebase return undefined in my component but I can see the object in console.log when I read my database?

我正在使用 Next.js 和 Typescript。

我正在嘗試實現一個自定義掛鈎來讀取我的數據並輸出 object。 我正在使用 firebase 實時數據庫。 我的數據是一個對象數組。 Firebase 返回一個 object 對象 with.val() 然后我將其轉換為自定義掛鈎中的對象數組,但由於某種原因我無法將其傳遞給我的組件。 我可以 console.log 新的對象數組,但不能將它返回到我的組件,當我在組件上 console.log 時讀取未定義。

我注意到有時當我編輯代碼並自動重新加載時,我的組件的 console.log 工作。

這是我的自定義鈎子片段和組件試圖調用它。 謝謝!

自定義鈎子片段:

// ... rest of hook is above this snippe (the hook is useFirebaseAuth())
  const readBlogData = () => {
    const db = getDatabase(app);
    const dbRef = ref(db, "blogs");
    let newArrObj;
    onValue(dbRef, (snapshot) => {
      newArrObj = Object.values(snapshot.val());
      console.log(newArrObj); // I can see the array of objects in console.log
    });

    return newArrObj;
  };

  return { login, logout, loginStatus, writeBlogData, readBlogData };
}

零件:

export default function BlogSection() {
  const { readBlogData } = useFirebaseAuth();
  console.log(readBlogData()); // console.log shows undefined

  return (
    <section className={styles.blogSection}>
      <Card className={styles.blogsContainer}>
        <h5>Blogs</h5>
        <Paginate blogs={DUMMY_DATA} />
      </Card>
    </section>
  );
}

onValue 回調中的代碼發生return newArrObj行之后。

您可能希望在您的鈎子中將其設置為 state 並返回該 state 以便消費者對其做出反應。

const [blogs, setBlogs] = useState([]);

// then

onValue(dbRef, (snapshot) => {
      newArrObj = Object.values(snapshot.val());
      setBlogs(newArrObj);
    });

// then

return { login, logout, loginStatus, writeBlogData, readBlogData, blogData: blogs };


對消費者進行編程以獲取數據並顯示響應

const Consumer = () => {
  const { blogData, readBlogData } = useWhatever();

  useEffect(() => readBlogData(), []); // Tell the hook to get some data

// blogData will initially be an empty array
// and then eventually will have some elements
return blogData.length ? <p>{JSON.stringify(blogData)</p> : null;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM