Reactjs React useEffect挂钩导致云Firestore中的读取量大幅增加

Reactjs React useEffect挂钩导致云Firestore中的读取量大幅增加,reactjs,firebase,google-cloud-firestore,react-hooks,Reactjs,Firebase,Google Cloud Firestore,React Hooks,当我使用下面的代码时,我看到云Firestore中的读取量从0到9.4K大幅增加 useEffect(() => { const getPostsFromFireStore = async () => { const posts = await getPosts(); setPosts(posts); }; getPostsFromFireStore(); }, []); 下面是getPosts函数 export const getPosts = ()

当我使用下面的代码时,我看到云Firestore中的读取量从
0
9.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);
  }
};
尽管如此,我还是在
useffect
hook中使用了
[]
作为依赖项。也就是说,在安装组件时,该效果应该只触发一次。此外,我还尝试将
[posts]
放在依赖项中,但结果更糟


这能更好地减少将要到firestore的呼叫吗?有人能帮忙吗?

这里的解决方案是使用清理功能来停止函数发出请求

解决方案:

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 

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