【问题标题】:React-router: Change URL and clear historyReact-router:更改 URL 并清除历史记录
【发布时间】:2017-02-04 12:49:20
【问题描述】:

我有以下场景:

用户打开激活链接;用户完成激活过程后,系统会将其移动到另一个页面。
我不想在浏览器的历史记录中保留激活链接,因为当用户返回时,他们将再次进入激活步骤。

如何替换浏览器的历史记录以从我的应用程序中删除某些请求?

【问题讨论】:

  • 最后,我可以通过以下语句解决:history.replaceState({}, document.title, url); props.router.replace(url);

标签: reactjs react-router


【解决方案1】:

HTML5 历史 API 提供了两种方法来Adding and modifying history entries

pushState() : 保留返回状态 replaceState() : 没有返回状态

假设您使用的是react-router。 所以,在你的组件上使用

this.props.history.replaceState('your new state')

阅读更多:Manipulating the browser history

视频:REACT JS TUTORIAL #6 - React Router & Intro to Single Page Apps with React JS

【讨论】:

  • 不幸的是,这对我不起作用。我有以下错误props.history.replaceState is not a function
  • @Alfrex92 现在是props.history.replace
【解决方案2】:

ReactJs 中,您应该为此使用browserHistory。这会处理您的历史记录,您无需自己实现这些功能。

browserHistory 有 2 个方法 push()replace() 与@fazal 在他的回答中提到的功能相同,但方式更好。

所以如果你想避免用户回到之前的状态,你需要使用browserHistory().replace

首先将其导入您的代码:

import {browserHistory} from 'react-router'

用户激活后,您执行以下操作:-

browserHistory.replace(//your new link)

【讨论】:

  • 你好,我试过这种方式,我仍然无法在浏览器上重写 url。 (我知道更改 url 不是 SPA 应用的常见行为。)
  • 更新:从 react-router v4 开始,这将不起作用。链接:github.com/ReactTraining/react-router/issues/4732
【解决方案3】:
window.location.href = 'Your path';

document.location.replace().

【讨论】:

  • 此答案不完整,请修改并提供详细信息
【解决方案4】:

我知道这是旧的,但我有一个类似的问题,其他答案都不是 100% 适用于我的版本或React,但这应该通过清除附加路径在更新的版本中工作。

   
  //replace(path, state)
  this.props.history.replace("/home", "urlhistory");

【讨论】:

  • 什么是“urlhistory”?我在文档中的任何地方都没有看到过这个?
【解决方案5】:

在你想改变路线的地方运行这个块

history.entries = [];
history.index = -1;
history.push(`/route`);

这将清除历史并更改为新的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2017-07-07
    • 2019-01-06
    • 2015-05-23
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多