javascript React.js:将整个状态同步到 localStorage

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21741754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:34:35  来源:igfitidea点击:

React.js: Syncing entire state to localStorage

javascriptlocal-storagestoragereactjs

提问by NVI

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.

我想将我的应用程序的状态存储在localStorage. 是否有回调或触发状态更改的事件?我会用它来调用localStorage.state = JSON.stringify(this.state). 可能,使用 0.5 秒节流。

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

TodoMVC React 示例使用 localStorage 作为存储。但是,它定义了事件处理程序中的保存和删除,例如keydownclick。就我而言,做同样的事情会产生很多样板。

回答by Sophie Alpert

In a componentDidUpdatelifecycle method you could serialize the state:

componentDidUpdate生命周期方法中,您可以序列化状态:

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).

每次组件重新渲染时都会运行该代码(每次 props 或状态更改都会发生这种情况)。