简体   繁体   English

滚动加载更多数据

[英]Load more data on scroll

I have a page with a search input, once the user clicks on submit the results come up.我有一个带有搜索输入的页面,一旦用户点击提交结果就会出现。

There can be a lot of results (usually not but there can be thousands of results) and I don't want to load them all at once, how can I get a few dozens and fetch more results from he API as the user scrolls down, what's the correct way to do that?可能有很多结果(通常不是,但可能有数千个结果)而且我不想一次加载它们,如何在用户向下滚动时从他的 API 中获取几十个并获取更多结果,这样做的正确方法是什么? I was thinking that Lodash throttle can fit but I couldn't find a good example for it.我在想 Lodash 油门可以安装,但我找不到一个很好的例子。

This is my react component:这是我的反应组件:

const getContacts = async (searchString) => {
  const { data: contactsInfo} = await axios.get(`api/Contats/Search?contactNum=${searchString}`);
  return contactsInfo;
};
export default class Home extends React.Component {
  state = {
    contactsInfo: [],
    searchString: '',
  };

  handleSubmit = async () => {
    const { searchString } = this.state;
    const contactsInfo = await getContacts(searchString);
    this.setState({ contactsInfo });
  };

  onInputChange = e => {
    this.setState({
      searchString: e.target.value,
    });
  };

  onMouseMove = e => {

  };

  render() {
    const { contactsInfo, searchString, } = this.state;
    return (
          <div css={bodyWrap} onMouseMove={e => this.onMouseMove(e)}>
            <Header appName="VERIFY" user={user} />
            {user.viewApp && (
              <div css={innerWrap}>
                <SearchInput
                  searchIcon
                  value={searchString || ''}
                  onChange={e => this.onInputChange(e)}
                  handleSubmit={this.handleSubmit}
                />
                     {contactsInfo.map(info => (
                      <SearchResultPanel
                        info={info}
                        isAdmin={user.isAdmin}
                        key={info.id}
                      />
                    ))}
              </div>
            )}
            <Footer />
          </div>

    );
  }
}

If the API supports pagination then you can use React-Infinite-Scroll .如果 API 支持分页,那么您可以使用React-Infinite-Scroll It looks like this看起来像这样

  <div style="height:700px;overflow:auto;">
    <InfiniteScroll
        pageStart={0}
        loadMore={loadFunc}
        hasMore={true || false}
        loader={<div className="loader">Loading ...</div>}
        useWindow={false}>
      {items}
    </InfiniteScroll>
  </div>

However if the REST API does not support it, you can still load the data and show them in chunks to the user with the same library but you would need to handle the current load state by yourself.但是,如果 REST API 不支持它,您仍然可以加载数据并将它们以块的形式显示给具有相同库的用户,但您需要自己处理当前的加载状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM