我是ReactJS的新手,我正在研究Pagination。我为分页制作逻辑,它与下一个按钮一起工作正常。我通过API获取服务器数据,API内置于环回。我想要的分页,如果用户在页面2
,它将显示第2页数据,如果用户想要下一个或点击3
分页它将移动到第3页并加载第3页数据。根据我的逻辑,它可以正常工作,就像我之前提到的那样,但当用户点击上一个按钮或从按钮3到按钮2时,它不会加载以前的页面数据。当用户点击上一个按钮时,它会加载下一页数据。我希望当用户点击按钮2时,它将加载第2页数据而不是下一页数据。
码
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' ))
每当您单击任何按钮时,this.state.skip将始终添加10.因此,当您从第3页单击按钮2时,它将加载第4页数据。
如果您想获得正确的数据。你应该像这样编辑功能btnClick。
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>
)
}