使用useEffect挂钩的无限滚动以先前的参数值运行

时间:2020-07-06 10:37:50

标签: javascript reactjs react-hooks infinite-scroll

我实现了以下无限滚动解决方案。尚未(尚未)针对1万多个项目进行优化,因此这超出了我的问题。

基本上有3种情况/情况会触发fetchMessage()

  1. 初始加载,Redux存储中没有数据
  2. 用户滚动并达到页面高度的80%
  3. 发生初始加载,但高度加载的内容不足以达到高度的80%/出现滚动条,因此用户无法滚动(因此我们无法看到下一页结果)

问题:案例(3)的标准非js行业解决方案是什么(我想用CSS强制最小高度)

错误:fetchMessage()使用相同的page运行两次,导致重复数据被加载。

const message = useSelector((state) => selectMessages(state)); // returns an array of objects to display
const page = useSelector((state) => selectPage(state)); // returns current page of results
const totalPages = useSelector((state) => selectTotalNumberPages(state)); // returns total number of result pages
const isFetching = useSelector((state) => selectIsFetching(state)); // boolean set to true when a fetch is triggered and to false when its complete

const fetchMessage = useCallback(() => {
    console.log("component page:", page);
    return dispatch(getMessagesIfNeeded(page));
  }, [dispatch, page]);

  const handleScroll = throttle(() => {
    console.log("scrolled");
    let d = document.body;
    let scrollTop = window.scrollY;
    let windowHeight =
      window.innerHeight || document.documentElement.clientHeight;
    let height = d.offsetHeight - windowHeight;
    let scrollPercentage = scrollTop / height;
    if (scrollPercentage > 0.8) {
      if (!isFetching && page <= totalPages) {
        fetchMessage();
      }
    }
  }, 1000);

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    return function cleanup() {
      window.removeEventListener("scroll", handleScroll);
    };
  });

  useEffect(() => {
    if (!message.length) {
      fetchMessage();
    }
  }, [fetchMessage, message]);

  useEffect(() => {
    const d = document.body;
    const bodyHeight = d.offsetHeight;
    let windowHeight =
      window.innerHeight || document.documentElement.clientHeight;
    if (windowHeight - bodyHeight > 200 && !isFetching && page <= totalPages) {
      fetchMessage();
    }
  }, [isFetching, fetchMessage, page, totalPages]);

我也有此问题的有效版本:https://codesandbox.io/s/recursing-noether-npp31?file=/src/message/MessageList.jsx

0 个答案:

没有答案