gpt4 book ai didi

reactjs - 更改 URL 中的单个参数

转载 作者:行者123 更新时间:2023-12-03 14:00:09 27 4
gpt4 key购买 nike

我希望能够创建指向我所在路线的链接,除了更改某些参数

在我的网站中,我决定采用如下结构的 URL:/list/:page(\d+)?/:filter?。现在,在我的组件中,我可以访问 match (使用 withRouter HOC)。在我的情况下它包含

{
isExact: true
params: {page: "3", filter: "duckbitt"}
path: "/listing/:page(\d+)?/:filter?"
url: "/listing/3/duckbitt"
}

这非常好,因为我有参数和路径。现在,这提出了 2 个问题:

  1. 是否有针对这种情况的react-router内置解决方案?

  2. 如果没有,是否有使用 path-to-regexp 的可能解决方案,或者我应该使用简单的搜索和替换?

最佳答案

当然,问题发布后就会立即出现解决方案。

import pathToRegexp from 'path-to-regexp';
// (...)
const toPath = pathToRegexp.compile(match.path);
const newPath = toPath({ ...match.params, page: 666 });
console.log(newPath); // "/listing/666/duckbitt"

关于reactjs - 更改 URL 中的单个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45383782/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com