React-router: Change URL and clear history

最后都变了- 提交于 2020-04-08 08:52:02

问题


I have the following scenario:

A user opens an activation link; after the user has completed the activation process, the system will move them to another page.
I don't want to keep the activation link in the browser's history because when the the user goes back they will get to the activation step again.

How do I replace the history of a browser to remove certain requests from my application?


回答1:


In reactJS you should use browserHistory for this purpose. This takes care of you histories and you dont need to implement those functions on your own.

browserHistory has 2 methods push() and replace() which do the same functions as @fazal mentioned in his answer but in a better way.

So if you want to avoid user going back to previous state you would need to use browserHistory().replace

Start with importing it into your code:-

import {browserHistory} from 'react-router'

After user has activated you do following:-

browserHistory.replace(//your new link)



回答2:


HTML5 history API provide two methods to Adding and modifying history entries.

pushState() : back state preserved replaceState() : no back state

Assuming you are using react-router. So, on your Component use

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

read more: Manipulating the browser history

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




回答3:


I know this is old but I had a similar issue and none of the other answers were 100% applicable with my version or React but this should work in more recent versions by clearing appended paths.

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



回答4:


Run this block where you want change route

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

This will clear the history and change for a new one.




回答5:


window.location.href = 'Your path';

or

document.location.replace().


来源:https://stackoverflow.com/questions/39715324/react-router-change-url-and-clear-history

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!