如何在URL中只替换最后一个路径

问题描述 投票:0回答:1

我用的是 react-router-dom v4.3.1.

例如,我有以下URL 我有以下网址 http://localhost:3000/url1/url2/url3

我只需要替换URL中的最后一条路径。/url3/mynewroute3

如何做到这一点 历史?

reactjs url react-router browser-history
1个回答
3
投票

使用 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('/') + '/new';

上文中采用的是当前窗口的位置路径,将最后一个窗口后的部分剪掉。/ 包括),并添加一个新的字符串(新路径)。

© www.soinside.com 2019 - 2024. All rights reserved.