1
4

2 回答 2

2

尝试将您的function进入useEffect回调:

  
  useEffect(() => {
    const getNextImages = (lastDocument) => {
      let query;
      !lastDocument
        ? (query = firebase
            .firestore()
            .collectionGroup("images")
            .where("showinapp", "==", true)
            .where("tags", "array-contains", tag)
            .orderBy("createdate", "desc")
            .limit(numImagesPerPage)
            .get())
        : (query = firebase
            .firestore()
            .collectionGroup("images")
            .where("showinapp", "==", true)
            .where("tags", "array-contains", tag)
            .orderBy("createdate", "desc")
            .startAfter(lastDocument)
            .limit(numImagesPerPage)
            .get());
      query
        .then((data) => {
          setIsLastPage(data.empty);
          setIsPending(false);
          setLastDocument(data.docs[data.docs.length - 1]);
          setGalleryData((galleryData) => galleryData.concat(data.docs));
        })
        .catch((error) => console.error(error));
    };
    getNextImages();
  }, [tag]);
于 2021-01-30T17:52:19.113 回答
0

现在我得到了解决方案。叫做useCallback钩子。

在玩弄了useCallback它的依赖数组之后,我只需要将函数包装getNextImages()在这个钩子中并设置它的依赖项(tag在这种情况下)。

然后我可以将该函数设置getNextImages为下面的钩子的依赖项useEffect……瞧:ESLint 现在很高兴(当然还有构建过程)。还防止了重新渲染和无限执行循环。

这是工作代码:

const getNextImages = useCallback(
    (lastDocument) => {
      let query;
      !lastDocument
        ? (query = firebase
            .firestore()
            .collectionGroup("images")
            .where("showinapp", "==", true)
            .where("tags", "array-contains", tag)
            .orderBy("createdate", "desc")
            .limit(numImagesPerPage)
            .get())
        : (query = firebase
            .firestore()
            .collectionGroup("images")
            .where("showinapp", "==", true)
            .where("tags", "array-contains", tag)
            .orderBy("createdate", "desc")
            .startAfter(lastDocument)
            .limit(numImagesPerPage)
            .get());
      query
        .then((data) => {
          setIsLastPage(data.empty);
          setIsPending(false);
          setLastDocument(data.docs[data.docs.length - 1]);
          setGalleryData((galleryData) => galleryData.concat(data.docs));
        })
        .catch((error) => console.error(error));
    },
    [tag]
  );

  useEffect(() => {
    getNextImages();
    setPageTitle(`Bilder zum Tag »${tag}«`);
    sendAnalytics("page_view", {
      page_title: `Bilder zum Tag »${tag}«`,
    });
  }, [getNextImages, tag]);
于 2021-01-31T08:46:46.360 回答