javascript - react : App requests same endpoint multiple times

标签 javascript reactjs react-hooks infinite-scroll

我正在使用Infinite scroll component 。它正在工作,但多次请求同一端点(3 -4 次)。根据我的 React 知识,让我解释一下发生了什么:

因为我设置了initialLoad={true},所以loadMore函数将在组件渲染后立即调用。我可以设置 initialLoad={false} 但它不会在初始渲染中获取数据

  1. 在第一次渲染中,它调用 loadMore 函数 ==> 正在加载 状态已更改 ==> 第二次渲染
  2. 在第二次渲染中,它调用 loadMore 函数 ==> tracks 状态已更改 ==> 第三次渲染
  3. 在第三次渲染中,它调用loadMore函数==>某些状态发生了变化==>第四次渲染

Index.js

export default function index() {
  const { tracks, error, loading, loadMore, hasMore } = usePublicTracks(
    myApiEndPoint.TRENDING_TRACKS,
    5,
  );

  return (
    <div>
      <Main>
        <InfiniteScroll
          initialLoad={true}  //call loadMore function right after component rendered
          pageStart={0}
          loadMore={loadMore}
          hasMore={hasMore}
        >
          <TrackList>
            {tracks.map((track, i) => (
              <TrackItem key={i}
                track={track}
              />
            ))}
          </TrackList>
          {loading && hasMore && (
            <div className="">
              <Spin />
            </div>
          )}
        </InfiniteScroll>
      </Main>
    </div>
  );
}

usePublicTracks.js

export const usePublicTracks = (endpoint, limit) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [offset, setOffset] = useState('');
  const [tracks, setTracks] = useState([])
  const [hasMore, setHasMore] = useState(true);

  console.log('tracks', tracks)
  const loadMore = async params => {
    try {
      console.log('hello22222222222222222222222222222222222222222')
      const res = await myApiAxiosInstance.get(endpoint, {
        params: {
          limit: limit,
          lastVisible: offset
        }
      });
      setLoading(false);
      setTracks([...tracks, ...(res.data.collection)])
      setOffset(res.data.lastVisible)
      if (res.data.lastVisible == "end") setHasMore(false);

    } catch (error) {
      setLoading(false);
      setError(error.message);
    }
  };



  return {
    error,
    loading,
    tracks,
    loadMore,
    hasMore
  };
};

当我将 loadMore 函数包装在 useEffect 中时,它显示错误 Hooks can only be called inside of a function component.:

const loadMore = async params => {
    useEffect(() => {
      const loadMoreOnce = async () => {
        //some logic
      };
      loadMoreOnce();
    }, []);
  };

我的问题是如何调用一次加载更多函数。然后每次滚动到窗口底部时调用它?如何防止多次请求同一端点?

最佳答案

const isLoading = false;
const myComponent = () => {
  useEffect(() => {
    loadMore(); // initial call, this useEffect equivalent to componentDidMount
  }, []);

  if (!isLoading && document.body.scrollTop >= document.body.offsetTop) { 
    console.log('loading, should see this once');
    isLoading = true;
    loadMore(); // here, after loadMore finished you need to resolve isLoading to false
  }
  return (<div>My component</div>);
}

尝试找到所有对loadMore函数的调用,也许在其他地方也调用了它,改变从页面开始的偏移量,检查hasMore条件是否正确,因为多个调用也可以来自InfiniteScroll本身,当它认为您多次触底。

关于javascript - react : App requests same endpoint multiple times,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59118956/

相关文章:

javascript - 为什么 React Context.Provider 是必需的(或有用的)?

javascript - 确定哪个依赖数组变量导致 useEffect 钩子(Hook)触发

读取文本文件时 C# SecurityException

javascript - 我们如何合并两个 instagram API 的结果

javascript - 如何在 ReactJS 中处理 div 上的 onKeyDown 事件

python - 无法从 React.js 数据网格中抓取数据

reactjs - 如何在传递空数组时将 useState 与 Typescript 一起使用

reactjs - TypeError : Cannot read property 'getPosts' of undefined - useQuery hook, react 功能组件

javascript - 将\n 替换为 JSON 字符串中的 <br>

javascript - 将 mozrequestfullscreen() 与多层 Canvas 一起使用?