最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论