我正在使用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<Map>()
移到Map()
本身,因为列表中的每个元素都有一个UUID,但是,我还没到那个时候。)
答案 0 :(得分:16)
您可以使用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可能会更有效率,因为此代码(与您的代码一样)必须迭代列表中的元素。
答案 1 :(得分:6)
根据@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;
});
});
}