如何在redux中深入更新Immutable Js Map中的两个值?

时间:2017-09-11 11:50:45

标签: reactjs redux updates immutable.js

我正在尝试更新width - >中的两个(x& items)值yrgroih9如下所示:

{
  appElements: {
    layers: {
      layer_1: {
        background: {
          width: '100px',
          height: '100px',
          bgColor: '#aaaaaa',
          bgImage: 'http:bgimage1.png'
        },
        items: {
          yrgroih9: {
             width: '100px',
             x: '200px',
             y: '200px'
           },
           qhy0dukj: {
             width: '100px',
             x: '200px',
             y: '200px'
           },
           '7lw2nvma': {
             width: '100px',
             x: '200px',
             y: '200px'
           }
        }
      }
    }
  }
}

用于更新内部新对象的代码 items - > yrgroih9

case 'UPDATE_OBJECT':
  return state.setIn(["appElements","layers","layer_1","items","yp57m359"],{
    ["width"]: action.objData.width,
    ["x"]: action.objData.x
  });

上述代码会移除当前位置y内的yrgroih9键,并更新widthx值。

在setIn之后排列的Redux存储数据:(来自chrome redux devtools): enter image description here

如何更新两个深度值而不删除其他键值。?

2 个答案:

答案 0 :(得分:3)

使用updateIn

如果您的项目是Immutable.js Map的实例:

case 'UPDATE_OBJECT':
  return state.updateIn(['appElements', 'layers', 'layer_1', 'items', 'yrgroih9'],
    (item) => item
      .set('width', action.objData.width)
      .set('x', action.objData.x)
  );

如果您的项目是纯JS对象:

case 'UPDATE_OBJECT':
  return state.updateIn(['appElements', 'layers', 'layer_1', 'items', 'yrgroih9'],
    (item) => ({
      ...item,
      width: action.objData.width,
      x: action.objData.x,
    })
  );

答案 1 :(得分:0)

state.setIn替换您给出的路径中的整个对象(appElements - > layers - > layer_1 - > items - > yp57m359)。您可以获取现有对象,修改字段,然后使用setIn:

const oldObject =
 state.hasIn(["appElements","layers","layer_1","items","yp57m359"])
   ? state.getIn(["appElements","layers","layer_1","items","yp57m‌​359"])
   : {};
const newObject = {
  ...oldObject,
  width: action.objData.width,
  x: action.objData.x
};
return state.setIn(["appElements","layers","layer_1","items","yp57m359"], newObject);