javascript - How to maintain react component state when goback from router? - Stack Overflow

I have two react ponents let say A and B. When A is shown on the page, user changes something on that p

I have two react ponents 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?

I have two react ponents 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?

Share Improve this question asked Aug 29, 2016 at 4:04 Joey Yi ZhaoJoey Yi Zhao 42.8k88 gold badges358 silver badges662 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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="/" ponent={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>
    );
  }
});

For this purpose you need to manage the state for whole application. Hence, you need to use redux for this purpose. Its not within my scope to say whole lot about redux in here but you can use redux and react-redux to manage such state by installing them from npm. Thanks

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744891002a4599412.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信