react+antd分页 实现分页及页面刷新时回到刷新前的page

antd框架地址:https://ant.design/index-cn

利用antdUI框架做了个分页,其他功能都没问题,但是页面跳转后刷新会回到第一页,经过学习,在组件里增加了hash值,详情请看代码,实现了页面跳转后刷新依然显示刷新前的页面。

import React from 'react'
import { Pagination, Spin } from 'antd' //引入分页组件
import 'whatwg-fetch'
import './agricultural.less' class Agricultural extends React.Component {
constructor(props) {
super(props)
this.state = {
agriculturalList: [],
currentData: [],
total: 0,
pageSize: 3,
pageNumber: parseInt(window.location.hash.slice(1), 0) || 1 //获取当前页面的hash值,转换为number类型
}
// 在react中点击事件里面 setState 时会使this重新定义,所以在点击的函数里面使用this.setState()时会报错this.setState not a function,因此需要提前给点击事件的函数绑定this
this.onPageChange = this.onPageChange.bind(this);
this.createMarkup = this.createMarkup.bind(this);
}
componentDidMount() {
this.handleAnchor() //页面刷新时回到刷新前的page
}
handleAnchor() {
this.onPageChange(this.state.pageNumber, this.state.pageSize); //手动调用onPageChange,传入当前页数和每页条数
} onPageChange(page, pageSize) {
this.setState({
pageNumber: page
}, () => {
window.location.hash = `#${page}`; //设置当前页面的hash值为当前page页数
})
} render() {
const agriculturalListData = this.state.currentData;return (
<div className="agricultural-layout">
// 你要显示的数据内容

//分页实现

<div className="pagination">
<Pagination
className="pagination-com"
showQuickJumper
hideOnSinglePage={ true }
defaultCurrent={ this.state.pageNumber }
current={ this.state.pageNumber }
total={ this.state.total }
pageSize={ this.state.pageSize }
onChange={ this.onPageChange }
showTotal={ (e) => {
return "Total " + e + " items"
} } />
</div>
</div>

        </div>
) } }
export default Agricultural;

react+antd分页 实现分页及页面刷新时回到刷新前的page

上一篇:HDOJ 5147 Sequence II 树阵


下一篇:PHPMailer发送邮件