【问题标题】:Best way to remove an element from a List inside of a Map in Immutable.js从 Immutable.js 中 Map 内的 List 中删除元素的最佳方法
【发布时间】:2015-07-03 06:34:18
【问题描述】:

我正在使用 Facebook's Immutable.js 来加速我的 React 应用程序以利用 PureRender mixin。我的数据结构之一是Map(),并且该映射中的一个键具有List<Map>() 作为其值。我想知道的是,不知道要从List() 中删除的项目的索引,删除它的最佳方法是什么?到目前为止,我已经想出了以下内容。这是最好(最有效)的方式吗?

// this.graphs is a Map() which contains a List<Map>() under the key "metrics"
onRemoveMetric: function(graphId, metricUUID) {
    var index = this.graphs.getIn([graphId, "metrics"]).findIndex(function(metric) {
        return metric.get("uuid") === metricUUID;
    });
    this.graphs = this.graphs.deleteIn([graphdId, "metrics", index]);
}

(我考虑将List&lt;Map&gt;() 本身移动到Map(),因为列表中的每个元素都有一个UUID,但是,我还没有到那个时候。)

【问题讨论】:

    标签: javascript immutable.js


    【解决方案1】:

    你可以使用Map.filter:

    onRemoveMetric: function(graphId, metricUUID) {
      this.graphs = this.graphs.setIn([graphId, "metrics"],
        this.graphs.getIn([graphId, "metrics"]).filter(function(metric) {
          return metric.get("uuid") !== metricUUID;
        })
      )
    }
    

    从性能的角度来看,切换到 Map 可能会更有效,因为这段代码(就像你的代码一样)必须遍历列表中的元素。

    【讨论】:

    • 当然比我的简洁多了!是的,你和我都有的解决方案,我认为如果不切换到Map,它不会变得更高效。
    • 您现在可以使用updateIn,而不是重复this.graphs.getIn([graphId, "metrics"])
    【解决方案2】:

    按照@YakirNa 的建议使用updateIn,如下所示。

    ES6:

      onRemoveMetric(graphId, metricUUID) {
        this.graphs = this.graphs.updateIn([graphId, 'metrics'],
          (metrics) => metrics.filter(
            (metric) => metric.get('uuid') !== metricUUID
          )
        );
      }
    

    ES5:

      onRemoveMetric: function(graphId, metricUUID) {
        this.graphs = this.graphs.updateIn([graphId, "metrics"], function(metrics) {
          return metrics.filter(function(metric) {
            return metric.get("uuid") !== metricUUID;
          });
        });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-01
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      相关资源
      最近更新 更多