首頁  >  文章  >  web前端  >  透過簡單的步驟掌握無限滾動

透過簡單的步驟掌握無限滾動

WBOY
WBOY原創
2024-08-18 07:04:351058瀏覽

Master Infinite Scrolling in Easy Steps

無限滾動

我們可以使用瀏覽器提供的 IntersectionObserver API 來實現無限滾動。
要實施,我們只需按照以下步驟操作:-

  1. 我們可以使用模擬 API 進行無限滾動,然後建立自訂鉤子
  2. 這個自訂鉤子將API的參數作為自己的函數參數。
  3. 然後我們就可以簡單的實作API呼叫了,使用useEffect和axios,傳入函數參數中的參數。
  4. 我們可以將 loading、error、hasMore 和 data 作為狀態
  5. 然後我們也可以使用 setTimeout 以便我們可以正確檢查載入以及無限滾動
  6. hasMore 將等於我們目前在頁面中顯示的資料數組的長度與我們從 api 呼叫獲取的資料相比
  7. 這有更多的功能,可以避免調用,即使我們到達資料末尾。
  8. 一旦自訂鉤子出現在我們的主頁中,我們將建立我們傳遞的參數的狀態
  9. 然後我們將參數傳遞給我們的自訂鉤子並檢索資料
  10. 我們得到的資料列表,我們將使用地圖渲染它,然後顯示它
  11. 現在,一旦到達末尾,我們就需要應用無限滾動,因此對於我們收到的數組的最後一個元素數據,我們只需添加一個引用
  12. 此引用相當於 useCallback 函數,其參數將是最後一個元素。
  13. 接下來我們將建立一個useRef,其值預設為null
  14. 現在我們將檢查是否處於載入狀態。如果是,我們將直接回傳
  15. 接下來我們將檢查這個 useRef 目前值是否為 null。如果不為空,我們將簡單地斷開該觀察者的連結。這裡的想法是觀察者每次都應該是新的,因為每次我們都會有新的數據
  16. 現在我們將透過新的 IntersectionObserver 來指派這個新的觀察者。回調函數的當前值。 IntersectionObserver API 將傳回一個回呼函數,以條目作為參數。
  17. 這些條目基本上是頁面中最後一個元素的值。我們想要與頁面中的這些條目互動時的條件
  18. 所以我們為每個條目都有一個布林值。相交
  19. 當這是真的時,我們將使自訂鉤子的參數發生變化。這將再次呼叫 api 並再次渲染
  20. 最後我們需要觀察我們在回調中傳遞的元素,因此如果我們有該元素,我們將簡單地觀察它。

程式碼

CustomHook.jsx

import axios from "axios";
import { useEffect, useState } from "react";
import { API_URL } from "../common/constants";

export const useAuthorList = (limit, page) => {
  const [isLoading, setIsLoading] = useState(false);
  const [authorList, setAuthorList] = useState([]);
  const [error, setError] = useState("");
  const [hasMore, setHasMore] = useState(true);

  useEffect(() => {
    setIsLoading(true);
    setTimeout(() => {
      axios({
        method: "GET",
        url: API_URL,
        params: { limit: limit, page: page },
      })
        .then((res) => {
          setAuthorList(res.data.data);
          setHasMore(res.data.data.length === limit);
          setIsLoading(false);
        })
        .catch((e) => setError(e));
    }, 500);
  }, [limit, page]);

  return [isLoading, authorList, error, hasMore];
};

App.jsx

import React, { useCallback, useRef, useState } from "react";
import { useAuthorList } from "./hooks/useAuthorList";
import { AuthorQuotes } from "./components/AuthorQuotes";

const App = () => {
  const [limit, setLimit] = useState(10);
  const [page, setPage] = useState(1);
  const [isLoading, authorList, error, hasMore] = useAuthorList(limit, page);

  const observer = useRef(null);
  const infiniteReference = useCallback(
    (element) => {
      if (isLoading) return;
      if (observer.current) {
        observer.current.disconnect();
      }

      observer.current = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting && hasMore) {
          setLimit((prev) => prev + 10);
        }
      });

      if (element) {
        observer.current.observe(element);
      }
    },
    [isLoading, hasMore]
  );

  return (
    <div className="author-quotes-list">
      {authorList.length > 0 &&
        authorList.map((authorQuotes, index) => {
          if (index + 1 === authorList.length) {
            return (
              <AuthorQuotes
                authorQuotes={authorQuotes}
                hasReference
                infiniteReference={infiniteReference}
              />
            );
          }
          return <AuthorQuotes authorQuotes={authorQuotes} />;
        })}
      {isLoading && <>Loading...</>}
    </div>
  );
};

export default App;

constants.js

export const API_URL = "https://api.javascripttutorial.net/v1/quotes/"

以上是透過簡單的步驟掌握無限滾動的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn