如何在React中更新URL中的查询参数?

维迪

我正在尝试使用react-js-pagination在我的Web应用程序中创建分页。分页显示在网页中,但我想根据像这样的页码更改url中的页面参数&page=4我尝试使用

this.props.history.push(`${window.location.search}&page=${pageNumber}`)

但这是&page=4每次我单击分页链接时附加的内容我知道这种更新网址的错误方法。如何仅根据url中的pageNumber更新页面参数?

handlePageChange = (pageNumber) => {
 this.setState({activePage: pageNumber});
 this.props.history.push(`${window.location.search}&page=${pageNumber}`)
}

<Pagination
    activePage={this.state.activePage}
    itemsCountPerPage={10}
    totalItemsCount={100}
    onChange={this.handlePageChange}
/>
Atef

您可以使用location.pathname代替,location.search但所有其他查询参数也将被删除。

因此,如果您还需要其他参数,而只想更改page参数,则可以使用URLSearchParamsjavascript对象,这将使替换当前分页更加容易。

因此,请执行以下操作:

创建一个包含当前URL和所有参数的新变量:

let currentUrlParams = new URLSearchParams(window.location.search);

然后将page参数更改为该变量中所需的值:

currentUrlParams.set('page', pageNumber);

现在,使用history.push以下命令使用新的参数推送当前网址

this.props.history.push(window.location.pathname + "?" + currentUrlParams.toString());

因此完整的代码将是:

let currentUrlParams = new URLSearchParams(window.location.search);
currentUrlParams.set('page', pageNumber);
this.props.history.push(window.location.pathname + "?" + currentUrlParams.toString());

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章