如何在ngrx中更新Map对象的状态

问题描述 投票:0回答:3

我在我的州有一处房产,即 Map 。 当我收到服务响应时,我希望更新此地图。 我在减速器中尝试过以下

 on(setMapData, (state, action) => {    
    const { data } = action  
    data.forEach( (value, id) => {
      let dataMap = state.dataMap
      dataMap.set(id, value)
      return {
        ...state,
        dataMap: {...state.dataMap, ...dataMap}
      }
    }) 
//Till here I can see dataMap having all the values in state.
    return {
      ...state
      //dataMap: state.dataMap
    }
// But nothing is returned from here, my selectors are not getting invoked.
  })

下面是我的状态对象

export const initialState: dataState = {
  loading: true,
  dataMap: new Map<string, object | 'error'>()
}

请帮助我解决这个问题。预先感谢。

angular ngrx ngrx-store ngrx-reducers
3个回答
0
投票

我可以想到两种解决方案:

  1. 使用
    Immer
    ImmutableJs
    在reducer处生成Map的副本,然后更新值。例如使用
    immer
    你的代码代码如下:

on(setMapData, (state, { data }) => {

    //Create a deep copy of the state dataMap and update it
    let dataMap = produce(state.dataMap, newData => {
        //loop through the received Map and get the new key,value pair
        data.forEach((value, key) => {
            //Set the new key, value pair of the map to the copied Map
            newData.set(key, value)
        });
    });

    //return the state with the new Map
    return { ...state, dataMap };
});
  1. 我认为这是最安全的方法:上面的用例与 ngrx-entity 提供的类似。尽量不要重新发明轮子,这个包将帮助您更新地图,而不必担心使用预定义方法的状态(实体是地图)。

0
投票

我可以告诉你,在操作中使用地图对象是行不通的。它始终显示为空。我不完全知道这是为什么,但我相信原因是,映射是一个可变对象。 Ngrx 根本不处理这些。例如,如果您在 Map 上使用 immutableJS,它将创建一个新的 Map()。

抱歉只回答了一半。


0
投票

这就是我所做的并且有效:

on(setUserPreferredFiltersMap, (state, { userPreferredFilter: userPreferredFilter }) => { const UpdatedUserFiltersMap = new Map(state.userPreferredFiltersMap); updateUserFiltersMap.set(userPreferredFilter.filterType, userPreferredFilter.data); 返回 { ...状态, userPreferredFiltersMap:更新的UserFiltersMap }; })

© www.soinside.com 2019 - 2024. All rights reserved.