在我的 react 应用程序中,我有一个需要分页的组件。我想做的是,实际上允许从 url 完成分页,而不仅仅是 ui。所以如果我去
localhost\users?page=2
我可以将链接分享给任何人,他们将被重定向到用户组件的第 2 页。
目前我正在做这样的事情
<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}
/>
)}
/>
我的路线模板看起来像这样
{ path: 'users/:id', element: <UsersList /> }
所以我实际上可以访问 localhost/users/2 ,但这不是我想要使用的正确的 URL 形式,它链接到 UserDetails 组件,并且应该保持这种方式。
我能够从 URL 中提取查询参数,但不知道如何使用它们
const query = useQuery();
const { page } = queryString.parse(query);
其中 useQuery
是包装 useLocation().search;
最佳答案
您应该在页面组件<中使用
this.props.location.search
或window.location.search
和URLSearchParams
/
用法:
const page = new URLSearchParams(this.props.location.search).get("page")
或者
const page = new URLSearchParams(window.location.search).get('page')
您可以传递给 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})
}
关于reactjs - React Router ,使用查询字符串分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66730490/