首页 > 解决方案 > 将 redux 存储保存到本地存储 - 使用 lit-element

问题描述

目前我正在尝试将我的 redux-state 的一个子集存储到 localstorage。我正在使用PWA Starter Kit中的文档来实现基本存储,目前它工作正常,但这只会将完整状态保存到本地存储。

这并不是我想要的,因为如前所述,我只想存储一个子集,比如一些特定的操作结果(例如state.settings,而不是state)。

每个文档和示例只存储完整的状态,我没有找到任何符合我需要的评论。

我目前的实现

redux-store.js

import {
  createStore,
  applyMiddleware,
  compose as origCompose,
  combineReducers
} from 'redux';
import thunk from 'redux-thunk';
import { lazyReducerEnhancer } from 'pwa-helpers/lazy-reducer-enhancer';
import { loadState, saveState } from './redux-localstorage';

import applicationReducer from './reducers/application-reducer';

export const store = createStore(
  (state, action) => state,
  loadState(),
  compose(lazyReducerEnhancer(combineReducers), applyMiddleware(thunk))
);

export default store;

store.addReducers({
  applicationReducer
});

store.subscribe(() => {
  saveState(store.getState());
});

redux-localstorage.js

const STORAGE = '__RDX_STORAGE_TEST__';

export const saveState = state => {
  const json = localStorage.getItem(STORAGE) || '{}';
  const stringifiedNewState = JSON.stringify(state);

  if (stringifiedNewState !== json && stringifiedNewState !== '{}') {
    localStorage.setItem(STORAGE, stringifiedNewState);
  }
};

export const loadState = () => {
  const json = localStorage.getItem(STORAGE) || '{}';
  const state = JSON.parse(json);
  return state || undefined;
};

所以,我的问题是:这甚至可能吗?如果是,我怎样才能做到这一点?

非常感谢。

标签: javascriptreduxlocal-storagelit-element

解决方案


使用基本的 PWA Starter Kit 作为基础,例如,如果您想存储商店状态和柜台状态而不是应用程序状态,您可以执行以下操作:

const STORAGE = '__RDX_STORAGE_TEST__';

export const saveState = state => {
  const json = localStorage.getItem(STORAGE) || '{}';
  // take only the parts we need
  const {shop, counter} = state;
  const stringifiedNewState = JSON.stringify({shop, counter});

  if (stringifiedNewState !== json && stringifiedNewState !== '{}') {
    localStorage.setItem(STORAGE, stringifiedNewState);
  }
};

export const loadState = () => {
  const json = localStorage.getItem(STORAGE) || '{}';
  const state = JSON.parse(json);
  return state || undefined;
};

这样只有这两个部分将被写入 localStorage


推荐阅读