Appearance
Redux 数据持久化解决方案
业务痛点分析
1、状态丢失问题:
用户登录信息存储在 Redux 中实现跨组件通信
页面刷新导致 Redux 状态重置,登录信息丢失
用户需要重新登录,体验不佳
2、手动同步问题:
手动同步状态到 Storage 方案繁琐且易出错
需要人为干预每个状态变更操作
Redux 持久化解决方案
- 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") || "{}");
}