【发布时间】:2018-05-21 06:20:22
【问题描述】:
我需要使用 LocalStorage 在 Redux 存储中保留多个状态。在我的情况下,我已经有一把钥匙,那就是驱动程序。还需要与公共汽车和运营商州有关。
Store.js
import ReduxThunk from 'redux-thunk';
import { createStore, applyMiddleware, compose } from 'redux';
import Reducers from './reducers';
import { loadState, saveState } from '../../utils/localstorage';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
// LOCAL STORAGE FOR DRIVERS, BUSES, CARRIERS
const persistedState = loadState()
const store = createStore(
Reducers,
persistedState,
composeEnhancers(
applyMiddleware(
ReduxThunk
)
)
);
store.subscribe(() => {
saveState({
drivers: store.getState().drivers
});
});
export default store;
localstorage.js
export const loadState = () => {
try {
const serializedDriversState = localStorage.getItem('drivers')
if (serializedDriversState === null) {
return undefined;
}
return JSON.parse(serializedDriversState);
} catch (err) {
return undefined;
}
};
export const saveState = (drivers) => {
try {
const serializedDriversState = JSON.stringify(drivers);
localStorage.setItem('drivers', serializedDriversState)
} catch (err) {
// Ignore errors.
}
}
我正在使用 Dan Abramov 的示例:Redux LocalStorage。
那么如何在 Redux store 中使用 LocalStorage 存储多个状态呢?是好方法还是使用redux-persist之类的中间件?
【问题讨论】:
-
您当前的解决方案有什么问题?
-
我需要再添加两个状态(公共汽车、运营商),使用这些键多次设置 locaStorage 项,但在我在 store.subscribe(() => 中写入的所有键中获得相同的第一个值{ saveSate({ }) }
标签: javascript reactjs redux local-storage