useEffect无法删除EventListener

时间:2019-04-26 05:05:58

标签: reactjs react-hooks

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”时删除滚动eventListener, 但是react挂钩会在每个useEffect中创建一个新函数hd。如果最后一页 在useLayoutEffect更改中,removeEventListener不起作用。

1 个答案:

答案 0 :(得分:0)

我们将需要监听isLastPage上的更改,并且仅在isLagePage为假时才添加事件监听器

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]);