简体   繁体   中英

Reactjs Refresh page

When I press the F5 button on my browser to refresh my page, I lose all the values that I once had in my state. How to keep the values updated in my State by pressing the F5 key

It is a bit tricky, but not impossible.

First, do this: Check if page gets reloaded or refreshed in Javascript

You need to recognize that your site has been reloaded and previous code might help you with that.

Next is, to pick place, where to store your state, before reload actually occurs. One option is to store it in local storage.

It is best, for you, if all data which you are trying to preserve, are on server already. If not, then you need some "middle point" between refreshes.

You could do something like this on the part where you recognize that store is reloading:

// Site is reloading
// Store information into users local storage... all current 
// states with information of url under which data is stored

On the place, when site is loaded again, you can do:

// Check if there is something stored in local storage for this specific site
// When yes, fill in the states again with configured data

Now, this can make you a lot of trouble, but it would do the work. For example, what about situations when you do not want to store your data.

I suggest that you describe here your use-case, and there might be some nicer approach to this problem.

I have a menu with submenus. I initialize all of my main menus in False to load the page to say that the sub menus are not open. When I click on a menu to display the sub-menu, I true it to say that the sub-menu is open

      componentWillMount (){
    {this.props.routes.map((prop, key) => {
      if(prop.subMenus != null){
        this.setState({
          [prop.code]:false
        });
      }
    })}
  }

As the other said you can save routes state in localStorage (it's like cookie, but better) To save something with localstorage

localStorage.setItem('routes', JSON.stringify(this.props.routes))

And in the componentDidMount method you can do that

const routesString = localStorage.getItem('routes');
const routes = routesString ? JSON.parse(routesString) : undefined

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