简体   繁体   中英

React.js: Syncing entire state to localStorage

I'd like to store my app's state in localStorage . Is there a callback or an event that fires on state change? I would use it to call localStorage.state = JSON.stringify(this.state) . Possibly, using 0.5 seconds throttling.

TodoMVC React examples uses localStorage as a storage. However, it defines saving and removing in event handlers such as keydown and click . For my case, doing the same would create a lot of boilerplate.

In a componentDidUpdate lifecycle method you could serialize the state:

componentDidUpdate: function(prevProps, prevState) {
    localStorage.state = JSON.stringify(this.state);
}

That code will be run each time the component rerenders (which happens with every props or state change).

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