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
不起作用。
我们需要听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]);