I have two react components let say A and B. When A is shown on the page, user changes something on that page which cause some states changed inside A. Then user click a button which navigate to B by router.push('/b')
. Then user click a back a back button and navigate the page to A which is done by router.goBack()
. Now the current URL is A but the previously updated states are gone. How can I maintain the state when user go back to A?
To maintain state after a page refresh in React, we can save the state in session storage. const Comp = () => { const [count, setCount] = useState(1); useEffect(() => { setCount(JSON. parse(window. sessionStorage.
Using componentDidUpdate method of React page lifecycle, you can handled or disabled go back functionality in browser. basically componentDidUpdate method will call automatocally when component got updated. so once your component is updated you can prevent to go back as below.
To go back to the previous page, pass -1 as a parameter to the navigate() function, e.g. navigate(-1) . Calling navigate with -1 is the same as hitting the back button. Similarly, you can call the navigate function with -2 to go 2 pages back.
I think you just need to enable BrowserHistory
on your router by intializing it like that : <Router history={new BrowserHistory}>
.
Before that, you should require BrowserHistory from 'react-router/lib/BrowserHistory'
I hope that helps !
var BrowserHistory = require('react-router/lib/BrowserHistory').default;
var App = React.createClass({
render: function() {
return (
<div>xxx</div>
);
}
});
React.render((
<Router history={BrowserHistory}>
<Route path="/" component={App} />
</Router>
), document.body);
Another way you can try is this,
this.context.router.goBack()
No navigation mixin required!
EDIT: Update with React v15 and ReactRouter v3.0.0 (Aug 20th, 2016):
var browserHistory = ReactRouter.browserHistory;
var BackButton = React.createClass({
render: function() {
return (
<button
className="button icon-left"
onClick={browserHistory.goBack}>
Back
</button>
);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With