useEffect无法removeEventListener [关闭]

问题描述 投票:0回答:1
function HomeList(props) {
  const [{data,isLastPage}, setData] = useState({
      data: [],
      isLastPage: false
  });
  const getData = () => {
    flag = false;
    request("/api/app/recommend", {
      params: {
        list_code: props.listcode,
        page,
        preview: 0
      }
    }).then(res => {
      let tmp = (res.msg === "lastpage" || isLastPage) ? true : false;
      if(tmp) {
        window.removeEventListener("scroll", hd);
      }
      setData(data => ({data:data.data.concat(res.data),isLastPage:tmp}));
      flag = true;
    });
    page++;
  };

  const onScroll = () => {
    const target = window.document.documentElement;
    const offsetH = target.offsetHeight;
    const scrollH = target.scrollHeight;
    const triggerH = scrollH * 0.5;
    const scrollTop = window.pageYOffset;
    //滚动过页面高度一半加一屏高度后加载数据
    if (scrollH - offsetH - scrollTop < triggerH) {
      if (flag) {
        getData();
      }
    }
  };

  const hd = throttle(onScroll, 500);
  useEffect(() => {
    getData();
    window.addEventListener("scroll", hd);
    return () => {
      window.removeEventListener("scroll", hd);
      page = 1;
      flag = true;
    };
  }, []);

  useLayoutEffect(() => {
      //here !!!!!!!!!!!!
      if(data.length < 18 && data.length > 0 && !isLastPage) {
          getData();
      }
  },[data])

我想在api msg为'lastpage'时删除scroll eventListener,但是反应钩子在每个useEffect中创建一个新的函数hd。如果在useLayoutEffect的最后一页改变,removeEventListener不起作用。

reactjs react-hooks
1个回答
0
投票

我们需要听isLastPage上的更改,我们只会在isLagePage为false时添加事件监听器

useEffect(() => {
  if (!isLastPage) {
    document.addEventListener('scroll', scroll);
  }
  return () => {
    // this cleanup function going to run when isLastPAge is about to change
    // useEffect capture the dependencies on render so we need to check if its 
    // not the last page because our dependency is about to change
    if (!isLastPage) {
      document.removeEventListener('scroll', scroll);
    }
  };
}, [isLastPage]);
© www.soinside.com 2019 - 2024. All rights reserved.