import { useEffect, useRef, useState } from "react"; import { Empty } from "@arco-design/web-react"; import { useSelector } from "react-redux"; import { useDispatch } from "react-redux"; import { setLoadingFalse } from "@/store/slices/loadingSlice"; const InfiniteScroll = ({ loadMore, hasMore, children, threshold = 50, className = "", }) => { const dispatch = useDispatch(); const containerRef = useRef(null); const globalLoading = useSelector((state) => state.loading.value); const [loading, setLoading] = useState(false); const handleScroll = () => { if (loading) return; setLoading(true); if (!containerRef.current || globalLoading || !hasMore) return; const { scrollTop, scrollHeight, clientHeight } = containerRef.current; if (scrollTop + clientHeight >= scrollHeight - threshold) { loadMore().finally(() => { dispatch(setLoadingFalse()); setLoading(false); }); } }; useEffect(() => { const container = containerRef.current; if (container) { container.addEventListener("scroll", handleScroll); // 初始加载时检查是否需要加载更多 handleScroll(); } return () => { if (container) { container.removeEventListener("scroll", handleScroll); } }; }, [loadMore, hasMore, threshold, globalLoading]); return (