You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中ngrx-store-localstorage无法还原LocalStorage中的Map

NgRx LocalStorage 加载 Map 对象问题解决

问题核心

JSON原生不支持Map类型,直接序列化Map时,因Map自身无枚举属性会被转为{},这就是刷新后状态变为空对象的原因。首次加载LocalStorage为空时状态为null符合初始设置,但错误的序列化逻辑导致刷新后异常。

解决方案

需通过自定义序列化/反序列化函数,明确标记并处理Map类型:

  1. 自定义序列化替换函数(replacer)
const replacer = (key: string, value: any) => {
  if (value instanceof Map) {
    return {
      __type__: 'Map',
      value: Array.from(value.entries()),
    };
  }
  return value;
};

将Map转为带类型标记的对象,避免被JSON.stringify处理为空对象。

  1. 自定义反序列化还原函数(reviver)
const reviver = (key: string, value: any) => {
  if (typeof value === 'object' && value !== null && value.__type__ === 'Map') {
    return new Map(value.value);
  }
  return value;
};

识别带__type__: 'Map'的对象,还原为Map实例。

  1. 配置NgRx localStorage meta-reducer
    在localStorageSync中指定上述两个函数:
export function localStorageSyncReducer(reducer: ActionReducer<State>): ActionReducer<State> {
  return localStorageSync({
    keys: ['yourFeatureKey'], // 替换为你的状态节点key
    replacer,
    reviver,
    rehydrate: true,
  })(reducer);
}

额外检查项

  • 确保reducer初始状态处理正确:若初始为null,需保证反序列化无数据时仍返回null,而非空对象。
  • 确认localStorageSync的keys指向包含Map的正确状态节点。

内容的提问来源于stack exchange,提问作者Frimlik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 12:25:59