Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何动态更改url的搜索部分_Reactjs_React Router_React Router Dom - Fatal编程技术网

Reactjs 如何动态更改url的搜索部分

Reactjs 如何动态更改url的搜索部分,reactjs,react-router,react-router-dom,Reactjs,React Router,React Router Dom,嘿,我有一个定制的钩子来处理分页中的页面更改。使用history.push在这个钩子中我只想替换page=“1”搜索的一部分。所以我不会覆盖搜索的其余部分 我正在使用react路由器5.1.2 使用分页 从'react router dom'导入{useHistory}; 导出常量usePagination=()=>{ const history=useHistory(); const onPageChange=(页码)=>{ log('usePagination中的当前历史路径名',histo

嘿,我有一个定制的钩子来处理分页中的页面更改。使用
history.push在这个钩子中我只想替换
page=“1”
搜索的一部分。所以我不会覆盖搜索的其余部分 我正在使用react路由器
5.1.2

使用分页

从'react router dom'导入{useHistory};
导出常量usePagination=()=>{
const history=useHistory();
const onPageChange=(页码)=>{
log('usePagination中的当前历史路径名',history.location.search);
历史推送({
路径名:history.location.pathname,
搜索:`page=${page}`,
});
};
返回{
改版,
};
};

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

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
  };
};