1

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

@observable questionnaire = {}

它有效,但我认为那是腰部。我只需要观察“选定”属性。这是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
              },
              ...
            ]
          }, ...
4

1 回答 1

3

一种方法是让一个Node类实现如下:

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);
  }
}

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

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

于 2016-10-15T17:11:38.253 回答