繁体   English   中英

从Immutable.js中的Map内部的List中删除元素的最佳方法

[英]Best way to remove an element from a List inside of a Map in Immutable.js

我使用Facebook的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<Map>()Map()本身,因为列表中的每个元素都有一个UUID,但是,我还没有。)

你可以使用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可能会更有效率,因为此代码(与您的代码一样)必须遍历列表中的元素。

使用@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;
      });
    });
  }

暂无
暂无

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

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