【问题标题】:React useEffect hook leads to huge spike in Reads in Cloud FirestoreReact useEffect hook 导致 Cloud Firestore 中读取量激增
【发布时间】:2021-02-16 11:23:30
【问题描述】:

当我使用以下代码时,我发现 Cloud Firestore 中的 Reads09.4K 出现了巨大的峰值。

useEffect(() => {
  const getPostsFromFireStore = async () => {
    const posts = await getPosts();
    setPosts(posts);
  };
  getPostsFromFireStore();
}, []);

这是getPosts 函数

 export const getPosts = () => {
  try {
    return db
      .collection('posts')
      .get()
      .then((querySnapshot) =>
        querySnapshot.docs.map((doc) =>
          Object.assign({ id: doc.id }, doc.data())
        )
      );
  } catch (e) {
    console.log('Error in fetching data', e);
  }
};

尽管如此,我还是在 useEffect 挂钩中使用了 [] 作为依赖项。意思是,当组件安装时,效果应该只触发一次。另外,我尝试将 [posts] 放入依赖项中,但情况变得更糟。

是否可以更好地减少将要发送到 Firestore 的调用?有人可以帮忙吗?

【问题讨论】:

  • 我看不出有什么问题。组件是否有可能被卸载然后重新安装?我想我们需要看到更多的代码。
  • 请编辑问题以显示整个代码 - 特别是 getPosts。问题中应该有足够的信息,以便任何人都可以重现该问题。
  • @DougStevenson 刚刚编辑了我的问题并添加了getPosts函数
  • 如果在不同的点添加日志会发生什么?这里到底发生了什么?帖子中有多少文档?
  • 我有 10 个文档。 @DougStevenson

标签: reactjs firebase google-cloud-firestore react-hooks


【解决方案1】:

一个清理函数来停止发出请求的函数将是这里的解决方案

解决方案:

const [mounted, setMounted] = useState(true);
//This will be helping us in the clean up function that will make in useEffect

useEffect(() => {
  const getPostsFromFireStore = async () => {
    const posts = await getPosts();
    setPosts(posts);
  };
  //First run this will hold make a request to you fireStore
  if (mounted){
    getPostsFromFireStore();
  }
  //Now you cleanup by setting mounted to false so hinder that function to render again
  return ()=>{
    setMounted(false);
  }  

}, [mounted]); //Our useEffect will be dependent on mounted change 

【讨论】:

    猜你喜欢
    • 2019-09-02
    • 2021-02-19
    • 2020-03-13
    • 2019-10-08
    • 2020-11-09
    • 2020-10-08
    • 2018-05-29
    • 2021-02-23
    • 1970-01-01
    相关资源
    最近更新 更多