我遇到了一个错误,无法识别哪里做错了,在我第一次加载期间 pagNum = 0 调用了两次,这导致前 3 个结果重复两次,然后当向下滚动 pageNum= 1、pageNum = 2 时,所有结果都正常工作。
我使用 python 作为我的后端和 mongo DB。
这是我的代码
import './App.css';
import { debounce } from 'lodash';
const App = () => {
const [videos, setVideos] = useState([]);
const [page, setPage] = useState(0);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
const limit = 3;
const [initialLoad, setInitialLoad] = useState(true); // New state to track initial load
useEffect(() => {
if (initialLoad) {
fetchVideos(page); // Initial load with page 0
setInitialLoad(false); // Set initialLoad to false after initial fetch
}
}, [page, initialLoad]); // Include page and initialLoad in dependency array
const fetchVideos = async (pageNum) => {
setLoading(true);
try {
const response = await fetch(`http://127.0.0.1:5000/videos?page=${pageNum}&limit=${limit}`);
const data = await response.json();
console.log('Fetched videos:', data);
if (data.length > 0) {
setVideos(prevVideos => [...prevVideos, ...data]);
setPage(pageNum + 1);
} else {
setHasMore(false);
}
} catch (error) {
console.error('Error fetching videos:', error);
} finally {
setLoading(false);
}
};
const handleScroll = useCallback(() => {
if (loading || !hasMore) return;
const lastVideo = document.querySelector('.video-list > .video-card:last-child');
if (!lastVideo) return;
const lastVideoOffset = lastVideo.offsetTop + lastVideo.clientHeight;
const pageOffset = window.pageYOffset + window.innerHeight;
const bottomOffset = 20;
if (pageOffset > lastVideoOffset - bottomOffset) {
fetchVideos(page);
}
}, [loading, hasMore, page]);
useEffect(() => {
const handleScrollDebounced = debounce(() => {
handleScroll();
}, 300);
window.addEventListener('scroll', handleScrollDebounced);
return () => window.removeEventListener('scroll', handleScrollDebounced);
}, [handleScroll]);
return (
<div className="App">
<h1>Music Reels</h1>
<div className="video-list">
{videos.map(video => (
<div className="video-card" key={video._id}>
<video controls autoPlay muted>
<source src={video.video_link} type="video/mp4" />
</video>
<div className="video-info">
<h2>{video.title}</h2>
<p>{video.description}</p>
<p>{new Date(video.uploaded_date).toLocaleDateString()}</p>
</div>
</div>
))}
{loading && <p>Loading...</p>}
{!loading && !hasMore && <p>No more videos</p>}
</div>
</div>
);
};
export default App;
如果有人可以帮助我。 :)
好吧,你可以清理一下 useEffect ,你现在正在使用 initalLoad 变量,你可以摆脱它并无条件使用 useEffect :
useEffect(() => {
fetchVideos(page); // Initial load with page 0
}, []);
这应该可以解决您的问题,首先您加载 0.. 然后在 fetchVideos 中,您将页面麻木地提高一并在滚动时触发。
这是我的想法,如果问题仍然存在,我将尝试在本地运行代码。