在 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);
})
您可以使用文档中所说的 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 ]
ImmutableJS 列表有一个名为 concat 的方法,其行为与普通的 javascript 数组相同。但是,您不能对不可变数组使用扩展语法。
push 的语法也不同于普通数组,push 就像 concat with Immutable List 返回一个新列表,你的 map 方法看起来像
b.map(v => {
a = a.push(v);
})
附言使用上面的方法虽然会改变你的数组
。如果要使用推送,则必须创建一个新列表,然后将数组内容推送到其中。然而a
是您的情况的最佳方式concat
在Immutable.js中添加List to List,可以使用
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);
在 https://measurethat.net/ 上运行测试后,似乎 concat 方法比 spread 更高效。
顺便说一下,spread 方法应该也可以,但是你需要转换回 ImmutableJS:
Immutable.fromJS([...a, ...b])
Concat 是本例中最直接、最简单的方法。