浏览器刷新后,Ngrx Store重置.如何使应用程序保留状态? [英] Ngrx Store Resets after browser refresh. How to make the application preserve the state?
问题描述
我从一个组件调度动作
this.store.dispatch({type : STORE_TEAMCREST , payload : team.crestURI});
在其他组件中,我使用
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
函数,该函数将在调度动作的任何时间被调用,并且状态树的某些部分可能已更改.对于一个简单的解决方案,您可以在此处将状态持久保存到本地存储中:
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};
}
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 Store重置.如何使应用程序保留状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!