Mobx 可观察深度对象

Mobx observable deep object

我正在寻找如何在深度 json 对象结构(例如树)数据树上实现 @observable 的最佳解决方案,数据树可能会非常深。每个节点都有很多属性,但我只需要在树节点中观察一个 属性 。只要我这样做

@observable questionnaire = {}

它有效,但我认为那是腰部。我只需要观察 'selected' 属性。 这是 json 结构。如果我错了请纠正我这里是问卷对象的简化。

[
  {
    "id": "1",
    "title": "level 1",
    "description": "text",
    "type": "Question",
    "selected": false,
    "childNodes": [
      {
        "title": "level 2",
        "description": "text",
        "type": "Question",
        "selected": false,
        "childNodes": [
          {
            "title": "level 3",
            "description": null,
            "type": "Question",
            "selected": false,
            "childNodes": [
              {
                "title": "level 4 1",
                "childNodes": [],
                "description": null,
                "type": "Checkbox",
                "selected": false
              },
              {
                "title": "level 4 2",
                "childNodes": [],
                "description": null,
                "type": "Checkbox",
                "selected": false
              },
              {
                "title": "level 4 3",
                "childNodes": [],
                "description": null,
                "type": "Checkbox",
                "selected": false
              },
              ...
            ]
          }, ...

一种方法是按如下方式实现 Node class:

class Node {
  @observable selected = false;
  @observable childNodes = asFlat([]);

  constructor(data) {
    // Recursively create `Node` objects for all children.
    data.childNodes = data.childNodes.map(child => new Node(child));
    Object.assign(this, data);
  }
}

然后从顶级 json 对象创建一个 Node 对象:new Node(json).

此解决方案将仅观察 selectedchildNodes。这并不理想,因为您需要将 json 对象包装在 Node 对象中。但我想不出任何其他方法。