首页  >  文章  >  web前端  >  通过简单的步骤掌握无限滚动

通过简单的步骤掌握无限滚动

WBOY
WBOY原创
2024-08-18 07:04:351061浏览

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