Ngrx 商店在浏览器刷新后重置.如何让应用保持状态? [英] Ngrx Store Resets after browser refresh. How to make the application preserve the state?
问题描述
我从一个组件分派一个动作
I Dispatch a action from one component
this.store.dispatch({type : STORE_TEAMCREST , payload : team.crestURI});
在另一个组件中,我使用
and in the other component i select from the store using
this.store.select(state => state.table.teamCrest).subscribe(data => this.teamCrest = data);
如果我的应用程序按顺序向后或向前运行,这可以正常工作,但是一旦我刷新浏览器,状态就会失去它的价值.如何保留它的值以便它在浏览器刷新时起作用?
This works fine if my app is going sequentially backward or forward, but once i do a browser refresh the state loses it's value. How to preserve it's value so that it works on browser refresh?
推荐答案
您的商店有一个 subscribe
函数,该函数将在任何时候调度 action 时被调用,状态树的某些部分可能是潜在的已经改变.对于一个简单的解决方案,您可以在此处将状态持久化到本地存储:
Your store has a subscribe
function which will be called any time an action is dispatched, and some part of the state tree may potentially have changed. For a simple solution, you could persist the state to local storage here:
this.store.subscribe(function() {
localStorage.setItem('state', JSON.stringify(this.store.getState()));
})
请注意,您需要对状态进行字符串化以将其存储在本地存储中
Notice that you will need to stringify your state to store it in local storage
要使用此状态,您需要将本地存储状态 localStorage.getItem('state')
(如果存在)作为您的减速器中的默认状态传递.为了实现这一点,我通常有一个辅助函数检查本地存储中是否存在键为state"的项目,如果存在则对该值调用 JSON.parse.
To use this state, you will need to pass the local storage state localStorage.getItem('state')
(if it exists) as your default state in your reducer. To achieve this, i normally have a helper function check whether an item with key 'state' exists in local storage and calls JSON.parse on the value if it exists.
默认减速器案例:
default:
if (retrieveState()) {
var newState = JSON.parse(retrieveState())
return newState
}
else {
return {...whatever your default state is};
}
此外,在快速浏览之后,似乎确实存在一个可以实现您想要的中间件:https://github.com/btroncone/ngrx-store-localstorage
Also after a quick look around, there does appear to exist a middleware which should achieve what you are wanting: https://github.com/btroncone/ngrx-store-localstorage
这篇关于Ngrx 商店在浏览器刷新后重置.如何让应用保持状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!