Mat*_*bst 9 javascript immutable.js
我使用Facebook的Immutable.js来加速我的React应用程序以利用PureRender mixin.我的一个数据结构是a Map(),该映射中的一个键具有List<Map>()as值.我想知道的是,不知道我要删除的项目的索引,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]);
}
Run Code Online (Sandbox Code Playgroud)
(我已经考虑过移动List<Map>()到Map()自己,因为列表中的每个元素都有一个UUID,但是,我还没到那个时候.)
Oll*_*liM 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;
})
)
}
Run Code Online (Sandbox Code Playgroud)
从性能的角度来看,切换到Map可能会更有效率,因为此代码(与您的代码一样)必须遍历列表中的元素.
使用@YakirNa建议的updateIn,如下所示.
ES6:
onRemoveMetric(graphId, metricUUID) {
this.graphs = this.graphs.updateIn([graphId, 'metrics'],
(metrics) => metrics.filter(
(metric) => metric.get('uuid') !== metricUUID
)
);
}
Run Code Online (Sandbox Code Playgroud)
ES5:
onRemoveMetric: function(graphId, metricUUID) {
this.graphs = this.graphs.updateIn([graphId, "metrics"], function(metrics) {
return metrics.filter(function(metric) {
return metric.get("uuid") !== metricUUID;
});
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14242 次 |
| 最近记录: |