reactjs - 仅替换 URL 中的最后一个路径部分

标签 reactjs url react-router browser-history

我正在使用 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在根组件中。
  • SO: Using React Router withRouter
  • Programmatically navigate with React Router

  • 做的时候history.push(...)路由器接收更改并对其采取行动。
    只更改 URL 的最后一部分;
    location.pathname.split('/').slice(0,-1).join('/') + '/newPath'
    
    正则表达式:
    location.pathname.replace(/[^/]*$/, newPath)
    
    以上取当前窗口位置路径,剪切最后一个/之后的部分(包括)并添加一个新字符串(新路径)

    关于reactjs - 仅替换 URL 中的最后一个路径部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53261092/

    相关文章:

    javascript - 在reactjs中滚动到页面顶部

    javascript - 使用 React 和 Semantic Ui 在 Javascript 中处理更改

    javascript - React-native - this.setState 仅在第二次单击后更新

    php - 如何检测 php curl 中的 URL Not Found 错误?

    javascript - 使用 Jest 测试时,componentWillUpdate 上的 nextState 不正确(还使用 react 路由器包装器)

    javascript - 在组件内 react :Unable to get this. state.name

    javascript - React+Jest - 测试异步组件并等待挂载

    reactjs - 如何使用 create-react-app 正确配置 material-ui 进行测试?

    javascript - Applescript 运行 Javascript 并在提示中插入文本

    javascript - 为什么 (&) 符号未显示在 Android 默认消息传递应用程序中?