将更新的对象关系保持在React状态

时间:2019-07-29 12:38:30

标签: javascript json reactjs relation

我试图弄清楚,我应该如何为React组件状态正确创建一个JSON模型。 从现在开始,我一直使用实体框架和虚拟属性来连接相关的“表”,所以现在当我想在React和JSON中做类似的事情时,我真的不知道如何继续。

这是我的简化模型:

{
  "myModel": {
    "Categories": [
      {
        "Id": 1,
        "Name": "Cat1",
        "Active": true
      },
      {
        "Id": 2,
        "Name": "Cat2",
        "Active": false
      }
    ],
    "Components": [
      {
        "Id": 1,
        "Name": "Component1",
        "CategoryId": 1
      },
      {
        "Id": 2,
        "Name": "Component2",
        "CategoryId": 1
      },
      {
        "Id": 3,
        "Name": "Component3",
        "CategoryId": 2
      }
    ]
  }
}

如何有效地结合这两个“表”? 例如,如果我要过滤ComponentsCategory的{​​{1}}?

在第二种方法中,我更改了模型以将整个Category对象包含在Component中:

Active

这使我可以非常轻松地使用..."Components": [ { "Id": 1, "Name": "Component1", "Category": { "Id": 1, "Name": "Cat1", "Active": true } },... 函数,但是问题是当我更改filter(a=>a.Category.Active==true)之一的属性时,更改不会反映到Categories

在这种情况下最好的方法是什么?最好在每次Components更改时更新所有Component[].Category或遍历所有类别,以在每次需要对CategoryId的组件进行过滤或分组时找到正确的类别?

我需要将Category放在单独的数组中,因为Categories并不总是使用它们。

2 个答案:

答案 0 :(得分:1)

您应该为此查看redux文档。您不应该复制数据并使其尽可能平整。因此,不建议您使用第二种方法,因为它既重复又嵌套了数据。组件应插入键为id的对象中。此外,您可以将所有活动组件保留在包含所有活动组件ID的字符串数组中,并通过迭代活动组件数组并从映射对象中提取具有ID的组件来检索它们。

答案 1 :(得分:1)

您可以使用数据结构轻松汇总数据并过滤活动组件:

  const activeComponents = myModel.Components.filter(component => {
    let isActive = false;
    const componentCategory = myModel.Categories.filter(
      category => category.Id === component.CategoryId
    );
    if (componentCategory.length && componentCategory[0].Active)
      isActive = true;
    return isActive;
  });

如果每个CategoryId始终都有一个Category,您也可以缩短代码:

  const activeComponents = myModel.Components.filter(
    component =>
      myModel.Categories.filter(
        category => category.Id === component.CategoryId
      )[0].Active
  );