React-router:更改 URL 并清除历史记录

Posted

技术标签:

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

我有以下场景:

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

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

【问题讨论】:

最后,我可以通过以下语句解决:history.replaceState(, document.title, url); props.router.replace(url); 【参考方案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`);

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

【讨论】:

以上是关于React-router:更改 URL 并清除历史记录的主要内容,如果未能解决你的问题,请参考以下文章

在页面 url 上创建事件已更改

React-router 和 iframe,浏览器历史

React-router history.push()已成功更改URL,但未将我的JXS内容重新呈现为具有匹配路径的正确Route内容

如何在页面重新加载时清除 react-router 中的 location.state?

带有 react-router 的 React.js:我的组件是不是应该对 url 的更改做出“反应”,反之亦然?

在不使用重定向或链接的情况下更改 react-router v4 中的 URL [重复]