React.js - 用分页分隔JSON返回

时间:2018-04-02 09:04:42

标签: json reactjs pagination

我在下面有这个组件,它工作正常。但我想在JSON返回的项目上插入分页,例如每页6张照片。我该如何解决?谢谢。

import React, { Component } from 'react'
import axios from 'axios'

const URL_HOUSES = 'http://localhost:3001/houses';

class Houses extends Component {
  constructor(props) {
  super(props)
  this.state = {
    houses: []
  }
}

componentDidMount() {
  axios.get(URL_HOUSES)
    .then(res => {
      this.setState({ houses: res.data })
    })
  }

render() {
  return (
    <div>
      {this.state.houses.map(item =>             
          <ul>
            {
              item.photos.map(photo => <li>{photo}</li>)
            }
          </ul>           
      )}
     </div>
   )
 }
}

 export default Houses;

2 个答案:

答案 0 :(得分:1)

试试这个

    import React, { Component } from 'react'
import axios from 'axios'

const URL_HOUSES = 'http://localhost:3001/houses';

class Houses extends Component {
  constructor(props) {
  super(props)
  this.state = {
    houses: [],
    currentPage: 1 //On Page change event increment this
  }
}

componentDidMount() {
  axios.get(URL_HOUSES)
    .then(res => {
      this.setState({ houses: res.data })
    })
  }

render() {
  var pageEnd = this.state.currentPage * 6;
  var pageStart = pageEnd - 6

  return (
    <div>
        //slice the array based on the current page
      {this.state.houses.slice(pageStart, pageEnd - 1).map(item =>             
          <ul>
            {
              item.photos.map(photo => <li>{photo}</li>)
            }
          </ul>           
      )}
     </div>
   )
 }
}

 export default Houses;

可能在语法上不正确,缺少一些检查,但我希望你明白这个想法

答案 1 :(得分:0)

 class Houses extends Component {
      constructor(props) {
      super(props)
      this.state = {
        houses: [],
        pageSize: 6,
        currentPage: 1,
      }
    }

    componentDidMount() {
      axios.get(URL_HOUSES)
        .then(res => {
          this.setState({ houses: res.data })
        })
      }

    render() {
     const { houses,pageSize, currentPage } = this.state
     const pageNo = Math.floor(houses.length / pageSize)
     const housesToDisplay = houses.slice((pageNo-1) * pageSize, ((pageNo-1) * pageSize) + pageSize))
      return (
        <div>
          {housesToDisplay.map(item =>             
              <ul>
                {
                  item.photos.map(photo => <li>{photo}</li>)
                }
              </ul>           
          )}
         </div>
       )
     }
    }

     export default Houses;

所以上面的实现是基本的实现。它可能有一些边缘情况,你需要小心。还有一件事,你需要添加分页按钮并将事件处理程序附加到按钮,这将更新处于反应状态的currentPage。想法是通用的。您可以阅读代码并了解。如果有任何疑问,请告诉我