使用react-router v4更改url中的参数之一

Pav*_*vel 6 reactjs react-router react-router-v4

我有一条这样的路

/cities/:cityGuid/responses/:responseGuid
Run Code Online (Sandbox Code Playgroud)

当用户更改城市时,我需要替换:cityGuid. 为了改变城市使用了一个NavLink组件。

<NavLink to="current url with changed cityGuid" text="Moscow" />
Run Code Online (Sandbox Code Playgroud)

为了获取当前 url,我需要使用location.pathname并替换cityGuid该字符串中的 a 。

current url: /cities/londonCityGuid/responses/abc1
user change city
next url is: /cities/moscowCityGuid/responses/abc1
Run Code Online (Sandbox Code Playgroud)

做这个的最好方式是什么?

Pav*_*vel 0

import pathToRegexp from 'path-to-regexp';

const { match: { path, params } } = this.props;

pathToRegexp.compile(path)({
  ...params,
  cityGuid: 'newCityGuid',
})
Run Code Online (Sandbox Code Playgroud)