React Router如何动态更改网址的搜索部分

时间:2020-09-07 18:14:08

标签: reactjs react-router react-router-dom

嘿,我有用于处理分页页面更改的自定义钩子。它在此挂钩中使用history.push,我只想替换搜索中的page="1"部分。因此,我不会覆盖其余的搜索 我正在使用反应路由器5.1.2

usePagination

import { useHistory } from 'react-router-dom';

export const usePagination = () => {
  const history = useHistory();
  const onPageChange = (page: number) => {
    console.log('current history pathname in usePagination', history.location.search);
    history.push({
      pathname: history.location.pathname,
      search: `page=${page}`,
    });
  };

  return {
    onPageChange,
  };
};

1 个答案:

答案 0 :(得分:1)

如果要保留所有其他查询搜索参数,则可以对当前/(page=)\d*/i值使用正则表达式search进行字符串替换。

search.replace(/(page=)\d*/i, `$1${page}`)

这将捕获一个组“ page =“,并匹配要替换的当前页面值。将捕获的组转发到结果($1)并注入新的页面值。 $1${page}解析为page=N,其中N是指定的页码

更新的挂钩代码

export const usePagination = () => {
  const { location: { pathname, search }, push } = useHistory();

  const onPageChange = page => {
    push({
      pathname,
      search: search.replace(/(page=)(\d*)/i, `$1${page}`)
    });
  };

  return {
    onPageChange
  };
};

Edit react-router-how-to-dynamically-change-search-part-of-url