我实现了以下无限滚动解决方案。尚未(尚未)针对1万多个项目进行优化,因此这超出了我的问题。
基本上有3种情况/情况会触发fetchMessage()
:
问题:案例(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