1

我有一个可无限滚动的组件,我希望它在用户滚动到页面底部时加载更多数据,但它只加载第一组数据然后停止。下面是我的代码:

import { Avatar, List, Spin, message } from 'antd';
import React, { Component } from 'react';

import InfiniteScroll from 'react-infinite-scroller';
import Services from '../../services/Services';

/**
 * infinitely scrollable timeline of uploaded content
 */
class Timeline extends Component {

  /**
   *
   * @param {*} props
   */
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      hasMore: true,
      data: []
    };
    this.fetchData = this.fetchData.bind(this);
  }

  /**
   * on load
   */
  componentDidMount() {
    this.fetchData();
  }

  /**
   * fetch the data
   */
  fetchData() {
    Services.getData()
        .then((response) => this.handleData(response))
        .catch((error) => this.handleError(error));
  }


  /**
   * handle the data
   * @param {*} response
   */
  handleData(response) {
    const data = this.state.data.concat(response.data);
    this.setState({ data: data });
  }

  /**
   * handle the infinite on load
   */
  handleInfiniteOnLoad() {
    this.setState({
      loading: true,
    });
    this.fetchData();
    this.setState({
      loading: false
    });
  };

  /**
   * handle any error
   * @param {*} error
   */
  handleError(error) {
    console.log(error);
  }

  /**
   * @return {*}
   */
  render() {
    return (
      <div className="demo-infinite-container">
        <InfiniteScroll
          initialLoad={false}
          pageStart={0}
          loadMore={this.fetchData}
          hasMore={!this.state.loading && this.state.hasMore}
          useWindow={true}
          loader={<div className="loader" key={0}>Loading ...</div>}
        >
          <List
            dataSource={this.state.data}
            renderItem={item => (
              <List.Item key={item.id}>
                <List.Item.Meta
                  avatar={
                    <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
                  }
                  title={<a href="https://ant.design">{item.id}</a>}
                  description={item.id}
                />
                <div>Content</div>
              </List.Item>
            )}
          >
            {this.state.loading && this.state.hasMore && (
              <div className="demo-loading-container">
                <Spin />
              </div>
            )}
          </List>
        </InfiniteScroll>
      </div>
    );
  }
}
export default Timeline;

该代码是从 ant design 复制的,但它使用的是我从后端检索到的我自己的数据。

提前致谢!

4

1 回答 1

1

我终于发现我需要为周围的 div 添加样式以使其可滚动,而不是整个页面都可滚动。代码如下:

<div className="demo-infinite-container" style={{ overflow: 'auto', padding: '8px 24px', height: '300px'}}>

于 2020-10-28T10:08:43.930 回答