javascript - 将 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;
};
所以,我的问题是:这甚至可能吗?如果是,我怎样才能做到这一点?
非常感谢。
解决方案
使用基本的 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
推荐阅读
- javascript - 如何使@submit 调用的函数起作用?
- python - Pyenv 在 Ubuntu 20.04 上找不到系统 python (3.8)
- java - 如果输入的数字不是一个快乐的数字,我怎么能得到一个错误的值?
- excel - 在通过切片器更改数据透视表之前运行代码
- node.js - 如何更改节点模块“say”的音频输出设备
- javascript - 如何在此 node.js 应用程序的警报中获取我的 err.message?
- python - 如何设置networkx线路长度?
- android - Android Paging3 改变页面大小
- javascript - 如何使用函数在html中打开链接
- excel - 当 4 个单元格不为空时启用命令按钮