react-redux中的持久化数据存储redux-persist
在React项目的开发中经常会遇到,保存一些当前页面的数据,
防止用户刷新导致页面出现报错或者是空白
详情页的数据,是通过列表页路由跳转传过来的id,去后台拿的数据
如果用户刷新当前页面,就会导致拿不到id,这个时候就会出现下面情况:
这个时候需要用到redux-persist,
```javascript
import { createStore, combineReducers, applyMiddleware, compose } from 'redux'
import reducers from './reducers'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2'
import thunk from 'redux-thunk'
import { playMode } from '../common/js/config'
import { loadSearch, loadPlay, loadFavorite } from '../common/js/cache'
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
//持久化配置
const persistConfig = {
key: 'globalData',
storage: storage,
stateReconclier: autoMergeLevel2,
blacklist: ['deviceData']//写在这块的数据不会存在 storage
}
const myPersistReducer = persistReducer(persistConfig, combineReducers(reducers))
const store = createStore(
myPersistReducer,
{
globalBackgroundColor:'#1890ff',//全局主题色
currentDeviceId:''//当前设备Id
},
composeEnhancers(applyMiddleware(thunk)))
export const persistor = persistStore(store)
export default store
之后改写reducer.js文件中的写法:
import {SET_CURRENT_DEVICE_ID} from './actions'
import {getStore, getStoreJSON} from "../utils/utils";
export default {
currentDeviceId(state={},action){
const { type, payload } = action;
switch (type) {
case SET_CURRENT_DEVICE_ID:
if(payload){
return {...payload}
}else{
return {...JSON.parse({...getStoreJSON('persist:globalData')}.currentDeviceId)}
}
default:
}
return state
}
}
在刷新之后,payload为undefined时候,我们以另一种方式返回id
最后无论我们怎么刷新,都不会丢失id