gpt4 book ai didi

javascript - Mobx可观察深度对象

转载 作者:行者123 更新时间:2023-12-02 14:05:56 26 4
gpt4 key购买 nike

我正在寻找如何在深层 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
},
...
]
}, ...

最佳答案

一种方法是按如下方式实现 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);
}
}

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

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

关于javascript - Mobx可观察深度对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40034522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com