useInfiniteScroll --- react scrolling loading

        useInfiniteScroll is a custom React Hook used to simplify the task of implementing infinite scroll functionality in React components.

        The basic idea of ​​infinite scroll is that instead of loading all the data at once, we load the data progressively as the user scrolls down the page. This gives the user the feeling of an endless list of content without having to wait for all the data to load at once.

        Use the useInfiniteScroll hook to handle the logic of detecting when the user scrolls to the bottom of the page and triggering a callback function to load more data. It also provides an easy way to manage the status of loading and error messages.


Here are some specific instructions for useInfiniteScroll:

        1: Parameters:

        useInfiniteScroll accepts a callback function as a parameter, which should be an asynchronous function to avoid blocking the user interface. When the user scrolls to the bottom of the page, useInfiniteScroll automatically calls this callback function to load more data. The callback function should return a Promise in order to use async/await syntax. For example:

const loadMoreData = async () => {
  // 加载更多数据的逻辑
  const response = await fetch('https://example.com/api/data?page=2');
  const newData = await response.json();
  return newData;
};

const [isFetching, setIsFetching] = useInfiniteScroll(loadMoreData);

        Callback functions can return any type of data, such as arrays, objects, etc., depending on the needs of your application. When using loaded data in a component, we usually need to store it in state so it can be rendered, like this:

function MyComponent() {
  const [data, setData] = useState([]);
  const [isFetching, setIsFetching] = useInfiniteScroll(loadMoreData);

  const handleLoadData = async () => {
    const newData = await loadMoreData();
    setData(prevData => [...prevData, ...newData]);
  };

  return (
    <div>
      {/* 渲染数据列表 */}
      {data.map(item => <div key={item.id}>{item.name}</div>)}

      {/* 显示正在加载的指示器 */}
      {isFetching && <div>Loading more data...</div>}
    </div>
  );
}

        2: Return value:

        useInfiniteScroll returns a boolean value and a function. A Boolean value that indicates whether the user is currently scrolling, and a function that enables or disables infinite scrolling.

  1. isFetching: A Boolean value indicating whether more data is being loaded.
  2. setIsFetching: A function that can be used to manually set the value of isFetching.

        You can use isFetching to display a loading indicator to let the user know that data is being loaded. For example, in the example above, we used isFetching to display the text "Loading" while loading more data, like this:

{isFetching && <div>Loading more data...</div>}

        When the data is loaded, isFetching will automatically be set to false.

       Three: Use:

        Using useInfiniteScroll in a component is simple. Just call useInfiniteScroll within the component and pass the callback function as a parameter. As follows:

import useInfiniteScroll from './useInfiniteScroll';

function MyComponent() {
  const loadMoreData = async () => {
    // 加载更多数据的逻辑
  };

  const [isFetching, setIsFetching] = useInfiniteScroll(loadMoreData);

  return (
    <div>
      {/* 渲染数据列表 */}
    </div>
  );
}

       Four: Component status:

        When using useInfiniteScroll, we also need to manage the state of the component, such as whether data is loading, whether an error occurred, etc. Therefore, it is usually necessary to define some state variables within components that use useInfiniteScroll to track these states.

     useInfiniteScroll component state includes:

  1. Whether all the data has been loaded.
  2. Current page number.
  3. Whether data is loading.

        The status of whether all data has been loaded is usually provided by the backend, and can be determined by judging whether there is a next page in the returned data.

        The current page number status can be determined based on the page number parameter passed each time the data is loaded.

        The status of whether data is being loaded can be represented by the isFetching status. When the data is being loaded, isFetching is true, and after the loading is completed, it is false.

        Five: Custom options:

        useInfiniteScroll also allows us to pass some custom options to customize its behavior. For example, we can specify the scroll trigger distance, initial state, etc.

     Here are some common options:

  1. threshold: Indicates the number of pixels required from the bottom of the window to the next request. The default value is 0.
  2. hasMore: Indicates whether there is more data. If set to false, the loading event will no longer be triggered.
  3. loader: Represents the component displayed when data is being loaded.
  4. useCapture: Indicates whether to execute the event in the capture phase, the default is false.

        In addition, you can also customize the parameters, request headers, request methods, etc. that need to be passed each time you load data. Specifically, all configurations that can be used in the fetch API can be used. For more information, see the section on custom Hooks in the React documentation.

Here's a simple example:

​
import { useState, useEffect } from 'react';
import useInfiniteScroll from './useInfiniteScroll';

function MyComponent() {
  const [data, setData] = useState([]);
  const [page, setPage] = useState(1);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  const loadMore = async () => {
    setIsLoading(true);
    try {
      const newData = await fetch(`https://example.com/data?page=${page}`);
      setData(data.concat(newData));
      setPage(page + 1);
    } catch (e) {
      setError(e.message);
    }
    setIsLoading(false);
  };

  const [isFetching, setIsFetching] = useInfiniteScroll(loadMore);

  return (
    <div>
      {data.map(item => (
        <div key={item.id}>{item.title}</div>
      ))}
      {isLoading && <div>Loading...</div>}
      {error && <div>{error}</div>}
    </div>
  );
}

​

        In this example, we have a component that displays a list of data loaded from an API endpoint. When the user reaches the bottom of the page, call the loadMore function to get the data for the next page.

        Use the useInfiniteScroll hook to detect when the user reaches the bottom of the page and trigger the loadMore function. Use the setIsFetching function to manage the state of the hook and track whether the user is currently scrolling.

        The isLoading and error status variables are used to display the loading spinner and error message while loading data.

 

 

 

Guess you like

Origin blog.csdn.net/weixin_40381947/article/details/132813720