【问题标题】:How to update list in list in ImmutableJS?如何在 ImmutableJS 中更新列表中的列表?
【发布时间】:2016-03-06 18:20:30
【问题描述】:

我在更新 ImmutableJS 列表中的列表时遇到问题。谁能告诉我我做错了什么?

var rows = Immutable.List();
for (var i = 0; i < 12; i++) {
  rows = rows.push({type:"floor"});
}

var cols = Immutable.List();
for (var j = 0; j < 12; j++) {
  cols = cols.push(rows);
}

var wall = {type:"wall"};

cols = cols.update(cols.get(3).get(4), function(wall) { return wall});

// I expect to get 'wall' written in the console, but the output is 'floor'.
console.log(cols.get(3).get(4).type);
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.6/immutable.js"&gt;&lt;/script&gt;

【问题讨论】:

  • "谁能告诉我我做错了什么?" - 你能告诉我们有什么问题吗?
  • 看起来你在这里什么都没做(至少没有你期望的):cols = cols.update(cols.get(3).get(4), function(wall) { return wall});(更新程序只是返回参数)

标签: immutable.js


【解决方案1】:

您可以将更新分为两个步骤(参见jsfiddle 上的示例):

var rows = Immutable.List();
for (var i = 0; i < 12; i++) {
  rows = rows.push({type:"floor"});
}

var cols = Immutable.List();
for (var j = 0; j < 12; j++) {
  cols = cols.push(rows);
}

var wall = {type:"wall"};
var nestedList = cols.get(3);
var newNestedList;
var newCols;
newNestedList = nestedList.update(4, function(item) {return wall});
newCols = cols.update(3, function(list) { return newNestedList});
console.log(newCols.get(3).get(4).type);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多