乐闻世界logo
搜索文章和话题

How to implement infinite scroll in next js?

1个答案

1

Implementing infinite scroll in Next.js typically involves the following steps:

  1. Pagination Handling: The server-side must support pagination and return data for specific pages based on the request.

  2. Frontend Scroll Detection: By listening to scroll events to detect when the user approaches the bottom of the page.

  3. Trigger Data Loading: Once the user scrolls near the bottom, initiate a request to fetch the next page of data.

  4. Update Page Content: Append the newly loaded data to the current page's content.

Specific implementation steps follow:

1. Create Pagination API (if not already implemented)

First, ensure your backend API supports pagination. For example, you might have an API endpoint that accepts the page number page and the number of items per page limit, like this:

shell
GET /api/items?page=1&limit=20

2. Set State and Effects

In your Next.js component, set up state variables to track the currently loaded data and page number.

javascript
import React, { useState, useEffect } from 'react'; const InfiniteScrollComponent = () => { const [items, setItems] = useState([]); // Store all items const [page, setPage] = useState(1); // Current page number const [loading, setLoading] = useState(false); // Whether loading is in progress // ... };

3. Write Data Loading Function

This function is called when the user is near the bottom to load the next page of data.

javascript
const loadMoreItems = async () => { if (loading) return; setLoading(true); const response = await fetch(`/api/items?page=${page}&limit=20`); const newItems = await response.json(); setItems([...items, ...newItems]); setPage(page + 1); setLoading(false); };

4. Implement Scroll Listener

In the component, use the useEffect hook to add and remove scroll event listeners.

javascript
useEffect(() => { const handleScroll = () => { if (window.innerHeight + document.documentElement.scrollTop !== document.documentElement.offsetHeight) return; loadMoreItems(); }; window.addEventListener('scroll', handleScroll); // Cleanup function return () => window.removeEventListener('scroll', handleScroll); }, [loading, page, items]); // Ensure dependencies are correctly set to avoid unnecessary calls or memory leaks

5. Display Data and Loading State

In the component's return function, render the current data list along with a loading indicator if needed.

javascript
return ( <> <ul> {items.map(item => ( <li key={item.id}>{item.content}</li> ))} </ul> {loading && <p>Loading more items...</p>} </> );

This is the basic structure for implementing infinite scroll, but in actual applications, you may need to adjust and optimize it based on specific requirements. For example, use a throttling function to prevent multiple data loading triggers during scrolling, and implement error handling mechanisms to manage failed API requests.

2024年6月29日 12:07 回复

你的答案