在Redux中使用LocalStorage保持多个状态

时间:2017-12-07 07:46:52

标签: javascript reactjs redux local-storage

我需要使用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商店中使用LocalStorage存储多个状态?是好方法还是使用像redux-persist这样的中间件?

1 个答案:

答案 0 :(得分:2)

我认为,你应该在store.subscribe函数中添加forEach over state,你可以部分保存整个商店。

export const saveState = (key, data) => {
  try {
    const serialized = JSON.stringify(data);
    localStorage.setItem(key, serialized);
  } catch (err) {
    // Ignore errors.
  }
}

store.subscribe(() => {
    const state = store.getState();
    Object.keys(state).forEach( key => {
      saveState(key, state[key])
    })
});