使用 Hooks 在 React 中重新渲染时停止/防止滚动到顶部(需要实现无限滚动)

gop*_*krm 3 infinite-scroll reactjs react-hooks

我正在尝试使用React Hooks设置无限滚动,我从节点后端正确获取数据(每个请求 3 个数据集),并且当我滚动时,新数据也会正确添加到数组中(在 returnedPlaces 状态下),但是页面在重新渲染时返回顶部,我需要防止这种行为。我该如何防止这种情况,下面是我的代码

import React, { useEffect, useState } from "react";
import "./App.css";

function App() {
  const [page, setPage] = useState(1);
  const [loadedPlaces, setLoadedPlaces] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const getPlaces = async () => {
      try {
        setIsLoading(true);
        const url = `http://localhost:5000/api/places/user/${id}?page=${page}&size=3`;
        const responseData = await fetch(url);
        const data = await responseData.json();
        console.log(data);
        setLoadedPlaces((prev) => [...prev, ...data.places]);
        setIsLoading(false);
      } catch (error) {}
    };
    getPlaces();
  }, [page]);

  window.onscroll = function (e) {
    if (
      window.innerHeight + document.documentElement.scrollTop ===
      document.documentElement.offsetHeight
    ) {
      setPage(page + 1);
    }
  };

  return (
    <div className='App'>
      <h1>Infinite Scroll</h1>
      {!isLoading &&
        loadedPlaces.length > 0 &&
        loadedPlaces.map((place, index) => (
          <div key={index} className={"container"}>
            <h1>{place.location.lat}</h1>
            <h1>{place.location.lng}</h1>
            <h1>{place.title}</h1>
            <h1>{place.description}</h1>
            <h1>{place.address}</h1>
            <hr></hr>
          </div>
        ))}
    </div>
  );
}

export default App;
Run Code Online (Sandbox Code Playgroud)

非常感谢任何帮助

San*_*hah 7

发生这种情况是因为每当您滚动时您都在调用

window.onscroll = function (e) {
    if (
      window.innerHeight + document.documentElement.scrollTop ===
      document.documentElement.offsetHeight
    ) {
      setPage(page + 1);
    }
  };
Run Code Online (Sandbox Code Playgroud)

它正在改变页数,改变页数会导致再次运行

 useEffect(() => {
    const getPlaces = async () => {
      try {
        setIsLoading(true);
        const url = `http://localhost:5000/api/places/user/${id}?page=${page}&size=3`;
        const responseData = await fetch(url);
        const data = await responseData.json();
        console.log(data);
        setLoadedPlaces((prev) => [...prev, ...data.places]);
        setIsLoading(false);
      } catch (error) {}
    };
    getPlaces();
  }, [page]);
Run Code Online (Sandbox Code Playgroud)

在该函数中,您这样做是setIsLoading(true)为了再次渲染它,因为


{!isLoading && <-----
        loadedPlaces.length > 0 &&
        loadedPlaces.map((place, index) => (
          <div key={index} className={"container"}>
            <h1>{place.location.lat}</h1>
            <h1>{place.location.lng}</h1>
            <h1>{place.title}</h1>
            <h1>{place.description}</h1>
            <h1>{place.address}</h1>
            <hr></hr>
          </div>
        ))}

Run Code Online (Sandbox Code Playgroud)

这会将您带到页面顶部

您可以尝试这种方法:

import React, { useEffect, useState } from "react";
import "./App.css";

function App() {
  const [page, setPage] = useState(1);
  const [loadedPlaces, setLoadedPlaces] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const getPlaces = async () => {
      try {
        setIsLoading(true);
        const url = `http://localhost:5000/api/places/user/${id}?page=${page}&size=3`;
        const responseData = await fetch(url);
        const data = await responseData.json();
        console.log(data);
        setLoadedPlaces((prev) => [...prev, ...data.places]);
        setIsLoading(false);
      } catch (error) {}
    };
    getPlaces();
  }, [page]);

  window.onscroll = function (e) {
    if (
      window.innerHeight + document.documentElement.scrollTop ===
      document.documentElement.offsetHeight
    ) {
      setPage(page + 1);
    }
  };

  return (
    <div className='App'>
      <h1>Infinite Scroll</h1>
       {
        loadedPlaces.length > 0 &&
        loadedPlaces.map((place, index) => (
          <div key={index} className={"container"}>
            <h1>{place.location.lat}</h1>
            <h1>{place.location.lng}</h1>
            <h1>{place.title}</h1>
            <h1>{place.description}</h1>
            <h1>{place.address}</h1>
            <hr></hr>
          </div>
        ))}
    </div>
  );
}

export default App;
Run Code Online (Sandbox Code Playgroud)