如何将新项目推送到 immutableJS 中的深层嵌套记录中

how to push a new item into a deeply nested Record in immutableJS

我正在尝试将新项目推送到深度嵌套的不可变记录中。

  const i = Immutable.Record({
    nested: new (Immutable.Record({
      someKey: [{id:1,name:'adam'}, {id:2,name:'steve'}],
    })),
  });
  const myMap = new i;
  const myNewMap = myMap.updateIn(['nested', 'someKey'], (fav)=>    fav.push({id:3,name:'dan'}));

  console.log(myNewMap.toJS());

我期望的是用新值更新嵌套列表,但实际输出是

  [object Object] {
  nested: [object Object] {
    someKey: 3
    }
  }

所以我做错了什么,那么我该如何用新值更新记录呢?

这里是示例的jsbin http://jsbin.com/nipolimuyu/edit?html,js,console

您在传递给 updateIn 的函数中缺少 return 语句(请注意 Array.push 不是 return 结果数组!)。应该是:

const myNewMap = myMap.updateIn(
  ['nested', 'someKey'], 
  (fav) => {
    fav.push({id:3,name:'dan'})
    return fav
  })

注意这里

你的初始对象应该都是一个不可变的JS对象。你可以使用 fromJS().

在您的示例中,您需要将数组添加为 ImmutableJS 列表

const i = Immutable.Record({
    nested: new (Immutable.Record({
    someKey: new Immutable.List([{id:1,name:'adam'}, {id:2,name:'steve'}]),
  })),
});
// The bad way, add a normal JS array to an immutableJS Record/map
const i = Immutable.Record({
    nested: new (Immutable.Record({
    someKey: [{id:1,name:'adam'}, {id:2,name:'steve'}],
  })),
});

所以最后你只需要按照你想要的去做

const myNewMap = myMap.updateIn(['nested', 'someKey'], fav => fav.push({id:3,name:'dan'}));

现在您可以使用 immutableJS push() 函数 return 一个新的 immutableJS 对象。