如何在ReactJS的前端实现分页?

时间:2018-01-24 17:46:18

标签: javascript json reactjs pagination

我使用ReactJS,NodeJS,MongoDB制作了板球网络应用程序。在前端,我每页显示来自JSON对象的数据,我想显示16个JSON对象。我使用.slice(0,16)方法从REST API中切割JSON对象,返回577个对象。现在我如何实现第2,3,4,5页的分页。

第2页 - >片(17,33) 对于第3页 - >片(34,49) 等等...

以下是我的webapp的代码和截图:

in content.js:

import React, { Component } from 'react';
import './content.css';

class Content extends Component {
    constructor(props){
        super(props);
        this.state = {
            matches:[],
            loading:true
        };
    }

    componentDidMount(){
        fetch('api/matches')
        .then(res => res.json())
        .then(res => {
      console.log(res)
      this.setState({
        matches:res.slice(0,16),
        loading:false
      })
    })
    }

    renderMatches() {
        return this.state.matches.map(match => {
            return (
                <div class="col-lg-3">
                    <div id="content">
                        <p class="match">MATCH {match.id}</p>
                        <h4>{match.team1}</h4>
                        <p>VS</p>
                        <h4>{match.team2}</h4>
                        <div class="winner">
                            <h3>WINNER</h3>
                            <h4>{match.winner}</h4>
                        </div>
                        <div class="stats">
                            <button type="button" class="btn btn-success">View Stats</button>
                        </div>
                    </div>
                </div>
            );
        })
    }

    render() {

        if (this.state.loading) {
            return <div>>Loading...</div>
        }

    return (
      <div>
          <div class="row">
            {this.renderMatches()}
          </div>
      </div>
    );
  }
}

export default Content;

在Pagination.js:

import React, { Component } from 'react';

class Pagination extends Component {

  render() {
    return (
      <div>
          <div class="container">
              <h2>Pagination</h2>
              <p>The .pagination class provides pagination links:</p>                  
              <ul class="pagination">
                <li><a href="#">1</a></li>
                <li><a href="#">2</a></li>
                <li><a href="#">3</a></li>
                <li><a href="#">4</a></li>
                <li><a href="#">5</a></li>
              </ul>
          </div>
      </div>
    );
  }
}

export default Pagination;

屏幕截图更清晰: enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

如何在组件状态下存储所有匹配项,并在呈现期间仅基于page查询字符串进行切片?

componentDidMount()中,在获取数据后,只需使用所有匹配项设置状态:

  this.setState({
    matches: res,
  })

然后,假设你想用url中的查询字符串来控制分页,例如:

?page=2

您可以在渲染():

中过滤匹配项
const RECORDS_PER_PAGE = 16;
const page = parseInt(getPageNumber(), 10) || 1; // defaults to 1 if no page query specified
const offset = (page - 1) * RECORDS_PER_PAGE

// do your mapping (do this in your renderMapping() method)
const matchComponents = this.state.matches.slice(0 + offset, RECORDS_PER_PAGE + offset).map(/* ... */);

其中getPageNumber()是一种为您提供页面查询字符串值的方法:

// Use your own query string parser if you wish
getPageNumber() {
  return window.location.search // <-- gives you access to the query parameters
  .slice(1) // remove the `?`
  .split("&")
  .reduce((queryHash, queryParam) => {

    // e.g. ?page=3 becomes ["page", "3"]
    const query = queryParam.split('=');
    return Object.assign({}, queryHash, ({
      [query[0]]: query[1] || null
    }));

  }, {}).page;
}