[英]React Router , pagination with query string
In my react app I have a component that requires pagination.在我的反应应用程序中,我有一个需要分页的组件。 What I would like to do, is to actually allow for pagination to be done also from the url, not only the ui.
我想做的是实际上允许从 url 进行分页,而不仅仅是 ui。 So if I go to
所以如果我 go 到
localhost\users?page=2
I could share the link to anyone and they will be redirected to page 2 of the users component.我可以将链接分享给任何人,他们将被重定向到用户组件的第 2 页。
Currently I'm doing something like this目前我正在做这样的事情
<Pagination
page={state.pageNo}
count={state.pageCount}
variant="outlined"
shape="rounded"
color="secondary"
showLastButton={state.pageCount > 7}
showFirstButton={state.pageCount > 7}
hideNextButton={state.pageCount === 1}
hidePrevButton={state.pageCount === 1}
onChange={onPageChange}
renderItem={pageItem => (
<PaginationItem
type={'start-ellipsis'}
component={Link}
selected
to={`${pageItem.page}`}
{...pageItem}
/>
)}
/>
And my route template looks something like this我的路线模板看起来像这样
{ path: 'users/:id', element: <UsersList /> }
So I can actually go to localhost/users/2
but this is not the right url form that I want to use, this is linked this to a UserDetails component and it should stay this way.所以我实际上可以 go 到
localhost/users/2
但这不是我想要使用的正确的 url 表单,它被链接到一个 UserDetails 组件,它应该保持这种方式。
I'm able to extract the query params from the URL, but don't know how to use them我能够从 URL 中提取查询参数,但不知道如何使用它们
const query = useQuery();
const { page } = queryString.parse(query);
where useQuery
is a helper function wrapping useLocation().search;
其中
useQuery
是一个帮助器 function 包装useLocation().search;
You should use this.props.location.search
or window.location.search
and URLSearchParams
in your Page Component
您应该在
Page Component
中使用this.props.location.search
或window.location.search
和URLSearchParams
Usage:用法:
const page = new URLSearchParams(this.props.location.search).get("page")
OR或者
const page = new URLSearchParams(window.location.search).get('page')
page
variable you can pass to your Pagination
component您可以传递给您的
Pagination
组件的page
变量
// Example
componentDidUpdate() {
const page = new URLSearchParams(this.props.location.search).get('page')
// for example you are maintaining page inside state then
this.setState({page})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.