小编gop*_*krm的帖子

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

我正在尝试使用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]); …
Run Code Online (Sandbox Code Playgroud)

infinite-scroll reactjs react-hooks

3
推荐指数
1
解决办法
5617
查看次数

标签 统计

infinite-scroll ×1

react-hooks ×1

reactjs ×1