我无法设置哪些元素将显示在js分页反应的页面上

时间:2019-05-28 10:50:58

标签: reactjs pagination

我尝试进行分页,但是没有发生。 我想我无法弄清楚在json数据上会出现多少页。

下面是我尝试做的示例的链接。

感谢那些有兴趣的人。

https://codesandbox.io/embed/kategori-detay-pagination-zpzdt

 handlePageChange(pageNumber) {
    console.log(`active page is ${pageNumber}`);
    this.setState({ activePage: pageNumber });
  }
 <Pagination
          prevPageText="prev"
          nextPageText="next"
          firstPageText="first"
          lastPageText="last"
          pageRangeDisplayed={10}
          activePage={this.state.activePage}
          itemsCountPerPage={10}
          totalItemsCount={totalPosts}
          pageRangeDisplayed={10}
          onChange={this.handlePageChange}
        />

1 个答案:

答案 0 :(得分:2)

您未将函数handlePageChange()与正确的'this'绑定

constructor(props) {
    super(props);
    this.state = {
      CategorySlug: "",
      CategoryBrief: [],
      Posts: []
    };

    // Need to bind the function to proper context
    this.handlePageChange = this.handlePageChange.bind(this);
}

handlePageChange(pageNumber) {
    console.log(`active page is ${pageNumber}`);

    // Without binding, 'this' refers <Pagination /> instance
    // With binding, 'this' refers to current <PageCategoryDetail /> instance
    this.setState({ activePage: pageNumber });
}

或者,如果您愿意,可以使用较新的语法,则不必绑定 每个功能分别

handlePageChange = (pageNumber) => {
    // Your code here
}

编辑

要显示项目,请根据所选页面,操作Posts数组并过滤出所需的项目

// You only filter by the selected Category, did not handle the paging
{Posts.filter(b => b.CategoryName === CategorySlug).map(item => (
   <li key={item.PostID}>{item.Title}</li>
))}

// You need further handle the pagination
const POST_PER_PAGE = 5
const pageOffset = this.state.activePage > 0 ? this.state.activePage - 1 : 0;
const startIndex = pageOffset * POST_PER_PAGE;
const endIndex = startIndex + POST_PER_PAGE;
{Posts.filter(b => b.CategoryName === CategorySlug).slice(startIndex, endIndex).map(item => (
   <li key={item.PostID}>{item.Title}</li>
))}

https://codesandbox.io/s/kategori-detay-pagination-f72px