loadState()&saveState()
loadState()
:按照对应的key: state
,从localStorage
中取出对应的字符串,将字符串解析成对应的JSONsaveState()
:接受一个state,将其序列化为字符串,存入localStorage
中1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20<!--localStorage.js-->
export const loadState = () => {
try {
const serializedState = localStorage.getItem('state');
if(serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (err) {
return undefined;
}
}
export const saveState = (state) => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
} catch (err) {
// Ignore write errors
}
}
Using localStorage.js
1 | // 取 |
Throttling saveState()
每一秒更新一次localStorage1
2
3
4
5
6
7import throttle from 'lodash/throttle'
store.subscribe(throttle(() => {
saveState({
todos: store.getState().todos
})
}, 1000))