繁体   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