Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain react component state when goback from router?

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?

like image 681
Joey Yi Zhao Avatar asked Aug 29 '16 04:08

Joey Yi Zhao


People also ask

How do I keep React component state after browser refresh?

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.

How do you prevent people from going back in React Dom Router?

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.

How do I go back using DOM On React Router?

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.


Video Answer


1 Answers

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>
    );
  }
});
like image 75
Md.Estiak Ahmmed Avatar answered Oct 13 '22 10:10

Md.Estiak Ahmmed