如何在redux-persist中同时配置localStorage和sessionStorage?

时间:2019-12-26 10:38:28

标签: reactjs redux react-redux session-storage redux-persist

我想将与用户相关的属性存储在sessionStorage中,并将其他属性存储在localStorage中。 我能够使用下面的配置通过persist将所有属性存储在localStorage中

import reducers from './reducer';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';

const persistConfig = {
key: 'root',
storage: storage,
stateReconciler: autoMergeLevel2 // see "Merge Process" section for details.
};

const pReducer = persistReducer(persistConfig, reducers);

有人可以告诉我如何在持久化模式下配置sessionStorage和localStorage吗?

3 个答案:

答案 0 :(得分:2)

除了Ivan的答案,您还可以使用session驱动程序。

import reducers from './reducer';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import sessionStorage from 'redux-persist/lib/storage/session'
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';

const rootPersistConfig = {
  key: 'root',
  storage: storage,
  blacklist: ['auth'],
  stateReconciler: autoMergeLevel2
};

const authPersistConfig = {
  key: 'auth',
  storage: sessionStorage,
}

const rootReducer = combineReducers({
  auth: persistReducer(authPersistConfig, authReducer),
  other: otherReducer,
})

export default persistReducer(rootPersistConfig, rootReducer)


答案 1 :(得分:0)

有时您只想在当前浏览器会话中缓存/持久化数据。关闭浏览器时,您希望缓存再次变空;但是在刷新浏览器标签时,您希望保持缓存完整无缺。例如,当用户登录到您的应用程序后处理用户会话时,此行为很有用。可以保存用户会话,直到关闭浏览器。您可以在此处使用本机sessionStorage而不是localStorage。会话存储的用法与本地存储的用法相同。

// Save data to sessionStorage
sessionStorage.setItem('key', 'value');

// Get saved data from sessionStorage
let data = sessionStorage.getItem('key');

// Remove saved data from sessionStorage
sessionStorage.removeItem('key');

// Remove all saved data from sessionStorage
sessionStorage.clear();

答案 2 :(得分:0)

官方redux-persist回购示例:

import { combineReducers } from 'redux'
import { persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'

import { authReducer, otherReducer } from './reducers'

const rootPersistConfig = {
  key: 'root',
  storage: storage,
  blacklist: ['auth']
}

const authPersistConfig = {
  key: 'auth',
  storage: storage,
  blacklist: ['somethingTemporary']
}

const rootReducer = combineReducers({
  auth: persistReducer(authPersistConfig, authReducer),
  other: otherReducer,
})

export default persistReducer(rootPersistConfig, rootReducer)

https://github.com/rt2zz/redux-persist#nested-persists

也许这不是您想要的,因为此解决方案基于嵌套化约简,但对我有用。