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

stop/prevent scrolling to top on re render in React using Hooks (need to implement infinite scrolling)

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

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;

非常感谢任何帮助

你可以添加这个。

function ScrollToBottom(){
  const elementRef = useRef();
  useEffect(() => elementRef.current.scrollIntoView());
  return <div ref={elementRef} />;
};

然后:

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>
        ))}
      <ScrollToBottom /> 
    </div>
  );

发生这种情况是因为无论何时滚动,您都在调用

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

它改变了页数,改变的页数再次导致 运行

 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]);

并且在该函数中,您正在执行 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>
        ))}

这会将您带到页面顶部

你可以试试这个方法:

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;