不可变,在映射内更新不返回正确的对象

Immutable, update inside map not returning correct object

本文关键字:返回 对象 更新 映射 不可变      更新时间:2023-09-26

我正在尝试编写一个函数来更新我拥有的不可变对象。我正在使用return myitem.updateIn,因此我可以将另一个更新链接到已经运行的更新之上。到目前为止,我有这个:

memo.updateIn(['Topics', 'filters'], function(topic) {
  topic.map(function(singleTopic) {
    singleTopic.update('filters', function(subTopicFilters) {
      subTopicFilters.map(function(singleSubTopic) {
        if(singleSubTopic.get('checked')){
            console.log("check", singleTopic.toJS());
            return singleTopic.set('checked', true);
        }
      })
    })
  })
});

里面的控制台日志点击了正确的部分,但是这似乎并没有像我想象的那样更新不可变的地图。psycological disorders中的checked值应设置为 true。请参阅此处的小提琴,例如 https://jsfiddle.net/alexjm/c5edxaue/27/。

对于某些上下文,这用于返回,其中将按这样的顺序在备忘录上运行几个单独的.update

returnModifiedData(memo) {
   return memo.update (....
   ).update( .....
   .update();

此功能是此过程的第一步,其他 2 个已经在工作。我不确定我做错了什么,无法正确更新它,可能是我试图在里面.set单个主题的?基本逻辑是检查主题是否具有内部选中的子主题,如果是,则检查主题。任何帮助将不胜感激。谢谢!

编辑:忘记添加备忘录本身的样子:

const memo = {
  "Topics": {
    "filters": {
      "Psychological disorders": {
        "checked": false,
        "filters": {
          "Anxiety disorders": {
            "filters": {},
            "checked": true
          }
        }
      },
      "test": {
        "checked": false,
        "filters": {
          "test": {
            "filters": {},
            "checked": false
          }
        }
      }
    },
    "isOpen": false
  }
};

如果你能解释你想要实现的逻辑是什么,那就更好了。

我会在这里猜测:

  1. 循环访问和更新 Topics->filters 中的项目。

  2. 对于迭代的每个singleTopic,进一步迭代其filters

  3. 如果它的任何singleSubTopic checkedtrue,请更新singleTopiccheckedtrue

以下是您可能期望的:

const map = {
  "Topics": {
    "filters": {
      "Psychological disorders": {
        "checked": false,
        "filters": {
          "Anxiety disorders": {
            "filters": {},
            "checked": true
          }
        }
      },
      "test": {
        "checked": false,
        "filters": {
          "test": {
            "filters": {},
            "checked": false
          }
        }
      }
    },
    "isOpen": false
  }
};
let memo = Immutable.fromJS(map);
memo = memo.updateIn(['Topics', 'filters'], function(topics) {
  // Remember to return the updated topics.
  return topics.map(function(singleTopic) {
    // If singleTopic has any of its singleSubTopic under filters have value checked=== true
    // update the singleTopic's checked, otherwise return unaltered.
    if (singleTopic.get('filters').some(function(singleSubTopic) {
      return singleSubTopic.get('checked');
    })) {
      return singleTopic.set('checked', true);
    }
    return singleTopic;
  });
});
console.log(memo.toJS());
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>