简体   繁体   中英

How can we use the same state across multiple tabs (pages)?

I have a page in my application that is an interactive chart with a bunch of settings (filters, time ranges, etc). I'd like to store them in-app state because some of the settings may be used by other components on another page, but right now if I click on any other tab and come back to the previous tab then the page shows the initial state(chart is gone, filtered data gone, date range showing the default value, dropdowns shows default ass well). And the state is also showing null .

Anything in your component state is dynamic; ie, it is temporary. If you refresh the window, the old state is lost. A similar thing happens when you open a fresh tab—you get the state declared in your constructor. You can use any of the following if you want the state data in another tab:

  1. Simply using redux won't solve your problem as redux store is also related to a specific browser tab. If you would like to persist your redux state across a browser refresh, it's best to do this using redux middleware. Check out the redux-persist , redux-storage middleware.

  2. If you are using react-router you can simply pass required state through the link when you open a fresh tab. Here's an example:

<Link to={{ 
  pathname: '/pathname', 
  state: { message: 'hello, im a passed message!' } 
}}/>
  1. Simply store the data in localStorage and access localStorage in other tabs.

If you are looking to use a variable across the entire application you can also use localStorage

localStorage.setItem('move', this.state.move);

also don't forget to unset it when you are done!

localStorage.removeItem('move');

The straight forward solution to this is redux-state-sync . It will just work and the store will be updated on all tabs and even windows on the browser.

I think you should implement react-redux into your app. React-redux is a state management tool that manage the state of your application at a centralized location and you access data from store at anytime from anywhere. React-redux: https://redux.js.org/basics/usage-with-react

You some library for state management. The most popular one that's used with React is redux.

https://redux.js.org/introduction

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