如何在Immutable.js中将列表添加到列表?

时间:2018-11-12 10:53:21

标签: javascript reactjs immutable.js

将列表添加到Immutable.js中的列表的最佳方法是什么?

concat方法有效,但另一种方法无效。

const a = fromJS([  
                {
                    comment: 'aaaa',
                    who: 'a1',
                    buttonInfo: ['a', 'b', 'c'],
                },
               {
                    comment: 'bb',
                    who: 'a2',
                    buttonInfo: ['a', 'b', 'c'],
                },
            ]);

const b = fromJS([  
                {
                    comment: 'ccc',
                    who: 'c1',
                    buttonInfo: ['a', 'b'],
                },
               {
                    comment: 'ddd',
                    who: 'd2',
                    buttonInfo: ['a''],
                },
            ]);

这有效:

a.concat(b)

但这不起作用:

[...a ,...b]

// or

b.map(v => {
  a.push(v);
})

3 个答案:

答案 0 :(得分:1)

您可以使用doc中所说的concat方法:

const list1 = List([ 1, 2, 3 ]);
const list2 = List([ 4, 5, 6 ]);
const array = [ 7, 8, 9 ];
const list3 = list1.concat(list2, array);
// List [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

答案 1 :(得分:0)

ImmutableJS列表具有一个名为concat的方法,其行为与普通的javascript数组相同。但是,不能对不可变数组使用扩展语法。

push的语法也与普通数组不同,像concat和Immutable List这样的push会返回一个新列表,您的map方法将类似于

b.map(v => {
   a = a.push(v);
})
  

P.S。但是,使用上述方法将使您的数组a发生变异。如果要使用push,必须创建一个新的List,然后将两个数组内容都推送到其中。但是concat是处理案件的最佳方法

答案 2 :(得分:0)

要在Immutable.js中将列表添加到列表,可以使用merge方法。

示例:

const a = fromJS(
  [  
    {
      comment: 'aaaa',
      who: 'a1',
      buttonInfo: ['a', 'b', 'c'],
    },
    {
      comment: 'bb',
      who: 'a2',
      buttonInfo: ['a', 'b', 'c'],
    },
  ]
);

const b = fromJS(
  [  
    {
      comment: 'ccc',
      who: 'c1',
      buttonInfo: ['a', 'b'],
    },
    {
      comment: 'ddd',
      who: 'd2',
      buttonInfo: ['a''],
    },
  ]
);


a.merge(b);