【问题标题】:How to paginate data?如何对数据进行分页?
【发布时间】:2019-06-09 17:59:15
【问题描述】:

如何实现分页以在页面上显示 10 个对象?这是我的沙盒:

https://codesandbox.io/s/rvo801wyp

【问题讨论】:

  • 检查你的链接,codesandbox.io/s/yv5rq51qrz
  • 我做了一些更改,添加了 show_list 状态,点击页面时只更新页面数据到状态并使用箭头函数绑定范围

标签: reactjs api pagination


【解决方案1】:

有两种方法可以实现这个目标,

  • 使用 API 进行分页

    制作 API 来处理一些请求参数,例如

     {
        **per_page_limit**: <no of record on a single page>,
        **current_page**: <current page number>,
        ....other request param
     }
    
  • 客户端分页

    获取所有记录并创建分页,为此获取列表长度并根据您的要求创建页面, 例如。总记录:100 每页限制:10,因此总页数为 10 现在只显示页面数据,使用 setState 和数据使用

    list_data_to_display = list.slice(0, page*limit)

    this.setState({slow_list: list_data_to_display})

handlePageChange=(pageNumber)=> {}

解决办法是:

this.state = {
      items: [],
      isLoading: false,
      activePage: 1,
      itemsCountPerPage: 1,
      totalItemsCount: 1,
      **show_list**: []
    };

show_list_data = () => {
    const show_list_data = this.state.items.slice(0, 10);
    this.setState({
      show_list: show_list_data
    });
  };

  componentDidMount() {
    fetch("https://demo9197058.mockable.io/users")
      .then(res => res.json())
      .then(json => {
        this.setState(
          {
            items: json,
            isLoading: true
          },
          this.show_list_data
        );
      });
  }
  handlePageChange = pageNumber => {
    console.log(`active page is ${pageNumber}`);

    const show_list_data = this.state.items.slice(
      (pageNumber - 1) * 10,
      pageNumber * 10
    );
    this.setState({
      show_list: show_list_data,
      activePage: pageNumber
    });
};

render() {
        var {  show_list, isLoading } = this.state;
        if (!isLoading) {
          return <div> loadding....</div>;
        } else {
          return (
            <div>
              <ul>
                {show_list.map(item => (

                ....
                ....

【讨论】:

    【解决方案2】:

    有两件事要做:

    1. 您需要在构造函数中绑定handlePageChange 或将其转换为箭头函数
    2. 添加一个切片以从items 中删除不会显示的数据.slice(this.state.activePage * this.state.itemsCountPerPage,(this.state.activePage + 1) * this.state.itemsCountPerPage)

    看看我对代码的改动:

    https://codesandbox.io/s/k58z3r9115

    我还在状态中动态添加了itemsCountPerPage

    【讨论】:

      猜你喜欢
      • 2011-10-02
      • 1970-01-01
      • 2016-03-29
      • 2022-01-21
      • 2023-04-01
      • 2020-02-18
      • 2016-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多