我正在使用 react-router-dom
v4.3.1
.
For example: I have the following URL
http://localhost:3000/url1/url2/url3
我只需要替换 URL 中的最后一条路由:
/url3
→ /mynewroute3
用历史怎么做?
最佳答案
使用 history.push
someMethod = () => {
const { history } = this.props;
history.push(`/url1/url2/url_new`); // change url3 to "url_new"
}
this.props
应该有 history
如果您使用的是 withRouter
在根组件中。做的时候
history.push(...)
路由器接收更改并对其采取行动。只更改 URL 的最后一部分;
location.pathname.split('/').slice(0,-1).join('/') + '/newPath'
正则表达式:location.pathname.replace(/[^/]*$/, newPath)
以上取当前窗口位置路径,剪切最后一个/
之后的部分(包括)并添加一个新字符串(新路径)
关于reactjs - 仅替换 URL 中的最后一个路径部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53261092/