蘑菇小姐会开花

redux persisting the state to the local storage

loadState()&saveState()

loadState():按照对应的key: state,从localStorage中取出对应的字符串,将字符串解析成对应的JSON
saveState():接受一个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
2
3
4
5
6
7
8
9
// 取
const store = createStore(todoApp, loadState())

// 存
store.subscribe(() => {
saveState({
todos: store.getState().todos
})
})

Throttling saveState()

每一秒更新一次localStorage

1
2
3
4
5
6
7
import throttle from 'lodash/throttle'

store.subscribe(throttle(() => {
saveState({
todos: store.getState().todos
})
}, 1000))

坚持原创技术分享,您的支持将鼓励我继续创作!