在React中滚动加载更多数据

时间:2018-11-27 07:18:19

标签: reactjs

我在一页中有大约700个项目的一系列数据。由于要通过滚动页面来获取大量数据,因此将加载其余数据,但无需滚动加载的所有数据。另一方面,我不想在此div <div ref="iScroll" style={{ height: "calc(50vh - 50px)", overflow: "auto"}}>中显示滚动条,而只显示浏览器的滚动条。实际上,我想通过滚动浏览器的滚动条来加载其余数据。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loadingState: false
    };
    $.ajax({
      url: "/hotel_react.bc",
      type: "post",
      data: {
        cityid: "1177676",
        fdate: "1397-09-11",
        tdate: "1397-09-14",
        userid: "0",
        rooms: JSON.stringify({
          rooms: [{ adultcount: "1", childcountandage: "0" }]
        })
      },
      success: result => {
        this.setState({ data: eval(result) });
      }
    });
  }

  componentDidMount() {
    this.refs.iScroll.addEventListener("scroll", () => {
      if (
        this.refs.iScroll.scrollTop + this.refs.iScroll.clientHeight >=
        this.refs.iScroll.scrollHeight
      ) {
        this.loadMoreItems();
      }
    });
  }

  renderHotel() {
    return this.state.data.map((item, i) => {
      return (
        <div class="item">
          <span>{item.total}</span>
        </div>
      );
    });
  }

  loadMoreItems() {
    this.setState({ loadingState: true });
    setTimeout(() => {
      this.setState({ data: this.state.data, loadingState: false });
    }, 3000);
  }

  render() {
    return (
      <div>
        <First />
        <div
          ref="iScroll"
          style={{ height: "calc(50vh - 50px)", overflow: "auto" }}
        >
          <ul>{this.renderHotel()}</ul>
          {this.state.loadingState ? (
            <p className="loading"> loading More Items..</p>
          ) : (
            ""
          )}
        </div>
      </div>
    );
  }
}

class First extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return "";
  }
}

ReactDOM.render(<App />, document.getElementById("Result"));

0 个答案:

没有答案