简体   繁体   English

使用react-redux的LocalStorage

[英]LocalStorage with react-redux

I'm using React and Redux for my SPA and I want to store some data locally. 我正在为我的SPA使用React和Redux,我想在本地存储一些数据。 And I need to synchronize appState with localstorage, so my data won't be lost after refreshing the page. 我需要将appState与localstorage同步,因此刷新页面后我的数据不会丢失。

I'm completely new for React and Redux and have not much of understanding what's going on, but as I think Redux creates for me that state of entire app, so I can't just bind my state with localstorage in app component because it'll be just state of component and not of my app. 我对React和Redux来说是全新的,并没有太多了解发生了什么,但是我认为Redux为我创建了整个应用程序的状态,所以我不能将我的状态与app组件中的localstorage绑定,因为它'我只是组件的状态而不是我的应用程序。

I can suggest you to store the state after each action. 我可以建议你在每次动作后存储状态。 For that you can use a localStorage middleware that only store the whole state object. 为此,您可以使用仅存储整个状态对象的localStorage中间件

Then in your createStore part you will retrieve the initialState from the localStorage API. 然后在createStore部分中,您将从localStorage API中检索initialState

In that case you don't need to modify any component, juste the initialState from localStorage and the middleware that save the state 在这种情况下,您不需要修改任何组件,从localStorage和保存状态的中间件中获取initialState

I would suggest storing the data in local storage with the following commands. 我建议使用以下命令将数据存储在本地存储中。

Set the data in localStorage can be done with the command: 在localStorage中设置数据可以使用以下命令完成:

localStorage.setItem('nameForData', variableNameForData);

To retrieve the data when required. 在需要时检索数据。

var variableNameForData = localStorage.getItem('nameForData')

To remove the data from localStorage: 要从localStorage中删除数据:

localStorage.removeItem('nameForData')

These would typically be put inside action creators with a dispatch to change the state of some Boolean that tracks the applications interaction with localStorage. 这些通常会放在动作创建器中,并带有一个调度来更改跟踪应用程序与localStorage交互的一些布尔值的状态。

For example you might have a state that is set to true when the local storage is created. 例如,在创建本地存储时,您可能具有设置为true的状态。

On refresh you might call an action creator that checks the local storage exists, and if it does set that boolean back to true or if it does not exist you are back to creating local storage and then set it to true. 在刷新时,您可以调用一个动作创建器来检查本地存储是否存在,如果它确实将该布尔值设置为true,或者如果它不存在,则返回创建本地存储,然后将其设置为true。

You could put this function in componentWillMount(){} and it will be called when the component is first rendered, and thus in the case of a refresh. 您可以将此函数放在componentWillMount(){} ,并在首次呈现组件时调用它,因此在刷新时也会调用它。

Docs for component life cycle and specifically componentWillMount here 组件生命周期的文档,特别是componentWillMount

Docs for local storage here 本地存储的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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