我用的是 react-router-dom
v4.3.1
.
例如,我有以下URL 我有以下网址
http://localhost:3000/url1/url2/url3
我只需要替换URL中的最后一条路径。/url3
→ /mynewroute3
如何做到这一点 历史?
someMethod = () => {
const { history } = this.props;
history.push(`/url1/url2/url_new`); // change url3 to "url_new"
}
this.props
本该 history
中,如果你使用的是 withRouter
在根部组件中。
当做 history.push(...)
路由器会接收到这个变化并进行操作。
location.pathname.split('/').slice(0,-1).join('/') + '/new';
上文中采用的是当前窗口的位置路径,将最后一个窗口后的部分剪掉。/
包括),并添加一个新的字符串(新路径)。