1

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. So if I go to

localhost\users?page=2

I could share the link to anyone and they will be redirected to page 2 of the users component.

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.

I'm able to extract the query params from the URL, but don't know how to use them

const query = useQuery();
const { page } = queryString.parse(query);

where useQuery is a helper function wrapping useLocation().search;

4

1 回答 1

1

你应该在你this.props.location.searchwindow.location.searchURLSearchParamsPage Component

用法:

const page = new URLSearchParams(this.props.location.search).get("page")

或者

const page = new URLSearchParams(window.location.search).get('page')

page您可以传递给Pagination组件的变量

// Example
componentDidUpdate() {
    const page = new URLSearchParams(this.props.location.search).get('page')
    // for example you are maintaining page inside state then
    this.setState({page})
}
于 2021-03-21T09:28:30.140 回答