You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ReactJS中对JSON数据切片实现分页功能?

Hey there! Let's get that pagination working smoothly. Here's a step-by-step fix to make your page links switch content correctly, with each page showing 16 items:

First, Fix the Content Component

We need to track the current page, keep the full dataset, and update the displayed matches when the page changes.

Update your Content.js like this:

import React, { Component } from 'react';
import Matchinfo from './matchinfo';
import Pagination from './Pagination'; // Add this import
import './content.css';

class Content extends Component {
 constructor(props){
 super(props);
 this.state = {
 matches:[],
 allMatches: [], // Store full dataset here
 loading:true,
 callmatchinfo: false,
 matchid:'',
 currentPage: 1 // Track active page
 };
 }

 componentDidMount(){
 fetch('api/matches')
 .then(res => res.json())
 .then(res => {
 console.log(res)
 const { currentPage } = this.state;
 const itemsPerPage = 16;
 // Standard pagination logic (continuous indices)
 const startIndex = (currentPage - 1) * itemsPerPage;
 const endIndex = startIndex + itemsPerPage;

 // If you *really* need to skip index 16 for page 2 (as you wrote), use this instead:
 // const startIndex = (currentPage - 1) * itemsPerPage + (currentPage > 1 ? 1 : 0);
 // const endIndex = startIndex + itemsPerPage;

 this.setState({
 allMatches: res, // Save full data
 matches: res.slice(startIndex, endIndex), // Slice for current page
 loading:false
 });
 })
 }

 // Handle page change from Pagination component
 handlePageChange = (pageNumber) => {
 const itemsPerPage = 16;
 const startIndex = (pageNumber - 1) * itemsPerPage;
 const endIndex = startIndex + itemsPerPage;

 // Use the alternate startIndex here if you need non-continuous slicing
 this.setState({
 currentPage: pageNumber,
 matches: this.state.allMatches.slice(startIndex, endIndex)
 });
 }

 viewstats(matchid){
 this.setState({
 callmatchinfo: true,
 matchid: matchid
 });
 }

 rendermatchinfo(){
 return <Matchinfo matchid={this.state.matchid} /> // Keep prop name consistent
 }

 renderMatches() {
 return this.state.matches.map(match => {
 return (
 <div className="col-lg-3" key={match.id}> {/* Add key for React list optimization */}
 <div id="content">
 <p className="match">MATCH {match.id}</p>
 <h4>{match.team1}</h4>
 <p>VS</p>
 <h4>{match.team2}</h4>
 <div className="winner">
 <h3>WINNER</h3>
 <h4>{match.winner}</h4>
 </div>
 <div className="stats">
 <button type="button" onClick={()=>{this.viewstats(match.id)}} className="btn btn-success">View Stats</button>
 </div>
 </div>
 </div>
 );
 })
 }

 render() {
 if (this.state.loading) {
 return <img src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif" />
 } else if(this.state.callmatchinfo){
 return <Matchinfo matchid={this.state.matchid} /> // Fix prop name mismatch
 }
 return (
 <div>
 <div className="row">
 {this.renderMatches()}
 </div>
 <div className="row">
 {this.state.callmatchinfo ? this.rendermatchinfo() : ''}
 </div>
 {/* Render Pagination and pass required props */}
 <Pagination currentPage={this.state.currentPage} onPageChange={this.handlePageChange} />
 </div>
 );
 }
}
export default Content;

Next, Update the Pagination Component

Make it interactive, pass click events back to Content, and highlight the active page:

import React, { Component } from 'react';

class Pagination extends Component {
  renderPageItems() {
    // Generate 5 page items dynamically
    return Array.from({ length: 5 }, (_, i) => i + 1).map(pageNumber => {
      const isActive = this.props.currentPage === pageNumber ? 'active' : '';
      return (
        <li className={isActive} key={pageNumber}>
          <a 
            href="#" 
            onClick={(e) => {
              e.preventDefault(); // Stop default link navigation
              this.props.onPageChange(pageNumber); // Trigger page update in Content
            }}
          >
            {pageNumber}
          </a>
        </li>
      );
    });
  }

  render() {
    return (
      <div>
        <div className="container">
          <ul className="pagination">
            {this.renderPageItems()}
          </ul>
        </div>
      </div>
    );
  }
}
export default Pagination;

Key Changes Explained

  1. Full Dataset Storage: We added allMatches to keep the complete list of matches, so we can slice it dynamically for each page (instead of only retaining the first 16 items).
  2. Page State Tracking: The currentPage state tracks which page the user is on, enabling dynamic content updates.
  3. Dynamic Slicing: For standard pagination, we calculate indices using (currentPage - 1) * itemsPerPage to ensure continuous, non-overlapping content. If you need the non-continuous slicing you mentioned (page 2 starts at index 17), use the alternate calculation commented out.
  4. Parent-Child Communication: The handlePageChange method is passed to Pagination, so clicking a page link triggers an update in the Content component.
  5. Active Page Highlight: We add the active class to the current page item for clear visual feedback.
  6. Consistent Props: Fixed the matchid prop name mismatch in the Matchinfo component to avoid unexpected bugs.

内容的提问来源于stack exchange,提问作者stone rock

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:57:33