我有一条这样的路
/cities/:cityGuid/responses/:responseGuid
当用户更改城市时,我需要替换:cityGuid
。要更改城市,请使用NavLink
组件。
<NavLink to="current url with changed cityGuid" text="Moscow" />
要获取当前网址,我需要使用location.pathname
并在此字符串中替换cityGuid
。
current url: /cities/londonCityGuid/responses/abc1
user change city
next url is: /cities/moscowCityGuid/responses/abc1
最好的方法是什么?
答案 0 :(得分:1)
如果要保留完整位置并在嵌套路由中更改某些参数,则可以使用pathToRegexp,匹配项的url和path以及位置的路径名来实现。
const ParamLink = ({
children,
match: { url = '', path = '', params: currentParams = {} } = {},
location: { pathname = '' } = {},
params = {}
}) => {
const urlPartToInsert = pathToRegexp.compile(path)({
...currentParams,
...params
});
const to = pathname.replace(url, urlPartToInsert);
return <Link to={to}>{children}</Link>;
};
export default ParamLink;
答案 1 :(得分:0)
import pathToRegexp from 'path-to-regexp';
const { match: { path, params } } = this.props;
pathToRegexp.compile(path)({
...params,
cityGuid: 'newCityGuid',
})