简体   繁体   中英

How do I retain state in a React component that gets mounted and unmounted?

Right now I have three main components in a sort of tab layout with a header on top, and which one of them is active is controlled in the top-level App component with a very simple hash router.

Now if I set a state in my Profile component that state will get thrown out if i switch to one of the other components.

How can I prevent that? Should I put the state on the App component instead or is this where something like Redux or Flux is helpful?

  Home   |   About   |   Profile
-----------------------------------
|                                 |
| Content                         |
...

Top level component:

function App(props) {
  switch (props.location[0]) {
    case '':
      return <Home />;
    case 'about':
      return <About />;
    case 'profile':
      return <Profile />;
    default:
      return <NoMatch />;
  }
}

App.propTypes = {
  location: React.PropTypes.array.isRequired,
};

function renderOnHashChange() {
  let location = window.location.hash.replace(/^#\/?|\/$/g, '').split('/');
  const application = <App location={location} />;

  ReactDOM.render(application, document.getElementById('app'));
}

window.addEventListener('hashchange', renderOnHashChange, false);

renderOnHashChange();

The simple answer is that you need to use some kind of store to retain the global state of your app. It's up to you what you choose; you've already identified some popular examples but there are more out there. Update the store by dispatching actions.

I would not recommend adding state to your top-level component, as this would require you to pass callbacks through every layer of application to call setState .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM