简体   繁体   中英

React : Pagination is not working properly

I am new to ReactJS and I am working on Pagination. I make logic for pagination, it working fine with the next button. I am fetching server data through API and API is built in loopback. What I want in pagination, If the user is on page 2 it will show page 2 data if the user wants to next or click on 3 in pagination it will move to page 3 and load page 3 data. With my logic, it works fine it doing same what I mentioned before but when the user clicks on the previous button or from button 3 to button 2 it not load previous page data. When the user clicks on the previous button it loading next page data. I want that when the user clicks on button 2 it will load page 2 data not next page data.

Code

     class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Item: 5,
      skip: 0
    }

    this.handleClick = this.handleClick.bind(this);
  }

  urlParams() {
    return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
  }

  handleClick() {
    this.setState({skip: this.state.skip + 1})
  }

  render() {
    return (
      <div>
        <a href={this.urlParams()}>Example link</a>
        <pre>{this.urlParams()}</pre>
        <button onClick={this.handleClick}>Change link</button>
      </div>
    )
  }
}


ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))

Whenever you click any button, this.state.skip will always add 10. So when you from page 3 click button 2 , it load page 4 data.

If you want to get the correct data. You should edit the function btnClick like this.

btnClick(page) {
   const userId=this.state.userId;
   const skip=this.state.skip;
   this.setState({
       userId,
       skip:(page - 1) * 10
   },()=> this.getData())
}



 const UserIdComponent=props=>{
  return(
    <button
        onClick={() => props.onClick(props.name)}
        value={props.name}>
        {props.name}
    </button>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM