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

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


在第一个渲染中,它调用loadMore函数==>加载状态已更改==>第二个渲染
在第二个渲染中,它调用loadMore函数==>跟踪状态更改==>第三个渲染
在第3个渲染中,它调用loadMore函数==>某些状态已更改==>第4个渲染


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
  };
};


当我在useEffect中包装loadMore func时,它显示错误Hook只能在函数组件的主体内部调用:

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


我的问题是如何一次调用load more函数。然后每次滚动到窗口底部时都调用它吗?如何防止多次请求同一终结点?

最佳答案

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 :应用程序多次请求相同的端点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59118956/

10-09 17:41