React 分页参数缓存,支持跳转返回当前分页

425 阅读1分钟

采用的方式是存在页面的url中,如

http://localhost:3000/#/list?page=1&pageSize=10

如果是ClassComponent,可以通过 withRouter 注入路由信息,然后通过 this.props.location.search 获取

class List() extends Component {
    constructor() {
        const search = this.props.location.search // ?page=1&pageSize=10
    }
}

export default withRouter(List)

如果是函数组件,则通过 useLocation 获取

let location = useLocation();
const search = location.href // ?page=1&pageSize=10

然后从 search 获取相关参数,不存在的参数为 null

const params = new URLSearchParams(search)
const page = params.get('page') // '1'
const pageSize = params.get('pageSize') // '10'
const total = params.get('total') // null

获取url参数就实现了,另外只需要在翻页等修改分页参数的时候,把参数更新到当前 route 去就可以了

// withRouter方式
this.props.history.push({
  pathname: '/list',
  search: `?page=${page}&pageSize=${pageSize}`
})

// useNavigate方式
let navigate = useNavigate()
navigate("/list", {
    search: `?page=${page}&pageSize=${pageSize}`
});

当从详情页返回到列表就是 http://localhost:3000/#/list?page=1&pageSize=10