简体   繁体   English

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

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

I'm trying to push a new item into a deeply nested immutable record. 我正在尝试将一个新项目推入一个深层嵌套的不可变记录中。

  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());

what I expect is to update the nested list with the new value, but the actual output is 我期望的是使用新值更新嵌套列表,但实际输出为

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

so Im doing something wrong, so how would I go about updating the record with the new value ? 所以我做错了什么,那么我将如何使用新值更新记录?

here is the jsbin for the example http://jsbin.com/nipolimuyu/edit?html,js,console 这是示例http://jsbin.com/nipolimuyu/edit?html,js,console的jsbin

You're missing return statement in a function you pass to updateIn (note that Array.push does NOT return a resulting array!). 您在传递给updateIn的函数中缺少return语句(请注意Array.push不会返回结果数组!)。 It should be: 它应该是:

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

Be careful here. 小心点

Your initial obj should all be an immutableJS obj. 您的初始obj应该都是immutableJS obj。 You can use fromJS(). 您可以使用fromJS()。

In your example, you need to add your array as an ImmutableJS list 在您的示例中,您需要将数组添加为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'}],
  })),
});

So at the end you just need to do like you wanted 所以最后您只需要按照自己的意愿去做

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

So now you can use the immutableJS push() function that return a new immutableJS object. 因此,现在您可以使用immutableJS push()函数返回一个新的immutableJS对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM