【问题标题】:Why do I get different results using withMutations?为什么我使用 withMutations 会得到不同的结果?
【发布时间】:2015-04-06 08:15:19
【问题描述】:

我是否误解了它的目的或它的工作原理?

var menuItems = Immutable.List.of(
  { parent_id: 0, id: 1 },
  { parent_id: 1, id: 2 },
  { parent_id: 1, id: 3 }
);

var results1 = menuItems
  .filter(function(menuItem) { return menuItem.parent_id === 1; }) // Filter out items with parent_id = 1
  .sort(function(childA, childB) { return childA.sort_order - childB.sort_order; }); // Sort them by sort_order

var results2 = menuItems.withMutations(function(list) {
  list
    .filter(function(menuItem) { return menuItem.parent_id === 1; }) // Filter out items with parent_id = 1
    .sort(function(childA, childB) { return childA.sort_order - childB.sort_order; }); // Sort them by sort_order
});

console.log(results1.size); // 2
console.log(results2.size); // 3

我的理解是它们会产生相同的结果,但 withMutations 由于操作链接会更快。

【问题讨论】:

    标签: javascript immutable.js


    【解决方案1】:

    你误解了withMutations。这样做的目的是为您提供一个临时游乐场,您可以在其中实际更改列表而不是创建副本。

    一个例子是:

    var results2 = menuItems.withMutations(function(list) {
      list.shift()
    });
    

    在您的代码中,您在withMutations 中使用filter。过滤器创建一个新数组并且不修改原始数组,因此您的withMutations 什么都不做。

    我认为你最好不要使用withMutations。如果在某些时候您认为“如果我可以修改数组而不是复制副本,这会容易得多”,您可以转向 withMutations。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2022-10-13
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多