Appearance
redux 数据持久化
痛点
- 用户的登录信息,一般情况下会存储在 redux 中,可以实现跨组件通信
- 唯一的缺点就是,当用户在刷新页面的时候,redux 中数据会全部初始化,导致登录信息丢失
设想
- 最开始的设想是每次在触发 dispatch 的时候,手动的存储一份到 Storage,这个虽然可以实现但是需要人为的去干预,不太智能,就放弃了这个方案。利用中间件的机制帮我们自动存储
思路
- 1、applyMiddleware 内部机制会把我们的中间件插件串联起来执行,利用闭包的特性把 store 封存在中间件内部
- 2、我们在编写自己的中间件时,在 dispatch 执行之后,再去获取 store.getState 存储在 Storage 中就可以实现自动注入
- 3、当页面刷新的时候,在 Storage 中取出数据初始化数据,保证数据不会丢失
js
import { createStore, applyMiddleware } from 'redux';
import { persistenceState,restoreState } from '../middleware';
import combinedReducer from './reducers';
const store = applyMiddleware(...,persistenceState() )( createStore )( combinedReducer,restoreState() )
js
export function persistenceState(storageType = "localStorage") {
return ({ getState }) => {
return (nextDispatch) => {
return (action) => {
nextDispatch(action);
try {
window[storageType].setItem(
"REDUX_PERSISTENCE",
JSON.stringify(getState())
);
} catch (error) {
console.log(error);
}
};
};
};
}
export function restoreState() {
return JSON.parse(localStorage.getItem("REDUX_PERSISTENCE") || "{}");
}