Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

How to make an infinite scrolling using ReactJs

I want to make an infinite scrolling. The idea is next, when user scroll at the bottom of the scroll area, the http request should occur and to add data to the previous, that exists before. In this way the user if will scroll back to the top will be able to see all options. For this i created:

import React, { useState } from "react";

import AsyncSelect from "react-select/async";

const WithPromises = () => {
  const [page, setPage] = useState(1);
  const [allData, setAllData] = useState([]); //here should be added all data
  const filterData = (inputValue) => {
    const req = fetch(
      `https://jsonplaceholder.typicode.com/todos?_limit=15&_page=${page}`
    )
      .then((response) => response.json())
      .then((res) => {
        console.log(res, "data");
        return res.map(({ title }) => {
          return {
            label: title,
            value: title
          };
        });
      });
    return req;
  };

  const promiseOptions = (inputValue) => {
    return filterData(inputValue);
  };

  const scroll = (e) => {
    setPage(page + 1); //when scroll is at the bottom
  };
  console.log(page);
  return (
    <AsyncSelect
      cacheOptions
      onMenuScrollToBottom={scroll}
      isClearable={true}
      isSearchable={true}
      defaultOptions
      loadOptions={promiseOptions}
    />
  );
};

export default WithPromises;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

react-virtualized have an InfiniteLoader HOC which you can use for the implementation of your infinite scrolling menu, let me give you an pseudocode:

function App() {
  const [items, setItems] = React.useState([]);
  const [rowCount, setRowCount] = React.useState(0);

  const rowRenderer = ({ key, index, style }) => (
    <div key={key} style={style}>
      {items[index]}
    </div>
  );

  const isRowLoaded = ({ index }) => {
    return !!items[index];
  };

  const loadMore = ({ startIndex, stopIndex }) => {
    fetch(`https://blahblahblah.com/getData?from=${startIndex}&to=${stopIndex}`)
      .then((res) => res.json)
      .then((response) => {
        setRowCount(response.data.count); //number of results!
        return response.data.items.map(({ title }) => ({
          label: title,
          value: title,
        }));
      })
      .then((formattedData) => setItems((prev) => [...prev, formattedData])); //add new datas to the previous list
  };
  return (
    <InfiniteLoader
      isRowLoaded={isRowLoaded}
      loadMoreRows={loadMore}
      rowCount={rowCount}>
      {({ onRowsRendered }) => (
        <List
          onRowsRendered={onRowsRendered}
          rowCount={rowCount}
          rowRenderer={rowRenderer}
        />
      )}
    </InfiniteLoader>
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...