2025-08-20 16:29:11 +08:00
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
|
|
|
import { Empty } from "@arco-design/web-react";
|
|
|
|
|
import { useSelector } from "react-redux";
|
|
|
|
|
import { useDispatch } from "react-redux";
|
2025-08-20 18:05:50 +08:00
|
|
|
import { setLoadingFalse } from "@/store/slices/loadingSlice";
|
2025-08-20 16:29:11 +08:00
|
|
|
|
|
|
|
|
const InfiniteScroll = ({
|
|
|
|
|
loadMore,
|
|
|
|
|
hasMore,
|
|
|
|
|
children,
|
|
|
|
|
threshold = 50,
|
|
|
|
|
className = "",
|
|
|
|
|
}) => {
|
|
|
|
|
const dispatch = useDispatch();
|
|
|
|
|
const containerRef = useRef(null);
|
2025-08-20 18:05:50 +08:00
|
|
|
const globalLoading = useSelector((state) => state.loading.value);
|
|
|
|
|
const [loading, setLoading] = useState(false);
|
2025-08-20 16:29:11 +08:00
|
|
|
|
2025-08-20 18:05:50 +08:00
|
|
|
const handleScroll = () => {
|
|
|
|
|
if (loading) return;
|
|
|
|
|
setLoading(true);
|
|
|
|
|
if (!containerRef.current || globalLoading || !hasMore) return;
|
2025-08-20 16:29:11 +08:00
|
|
|
|
2025-08-20 18:05:50 +08:00
|
|
|
const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
|
2025-08-20 16:29:11 +08:00
|
|
|
|
2025-08-20 18:05:50 +08:00
|
|
|
if (scrollTop + clientHeight >= scrollHeight - threshold) {
|
|
|
|
|
loadMore().finally(() => {
|
|
|
|
|
dispatch(setLoadingFalse());
|
|
|
|
|
setLoading(false);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
};
|
2025-08-20 16:29:11 +08:00
|
|
|
|
2025-08-20 18:05:50 +08:00
|
|
|
useEffect(() => {
|
2025-08-20 16:29:11 +08:00
|
|
|
const container = containerRef.current;
|
|
|
|
|
if (container) {
|
|
|
|
|
container.addEventListener("scroll", handleScroll);
|
|
|
|
|
// 初始加载时检查是否需要加载更多
|
|
|
|
|
handleScroll();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
|
if (container) {
|
|
|
|
|
container.removeEventListener("scroll", handleScroll);
|
|
|
|
|
}
|
|
|
|
|
};
|
2025-08-20 18:05:50 +08:00
|
|
|
}, [loadMore, hasMore, threshold, globalLoading]);
|
2025-08-20 16:29:11 +08:00
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
<div
|
|
|
|
|
ref={containerRef}
|
|
|
|
|
className={`infinite-scroll-container ${className}`}
|
|
|
|
|
>
|
|
|
|
|
{children}
|
2025-08-20 18:05:50 +08:00
|
|
|
{!hasMore && !globalLoading && <Empty description="没有更多了" />}
|
2025-08-20 16:29:11 +08:00
|
|
|
</div>
|
|
|
|
|
);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export default InfiniteScroll;
|