gpt4 book ai didi

javascript - 在 React 状态中保持更新的对象关系

转载 作者:行者123 更新时间:2023-12-01 00:47:31 25 4
gpt4 key购买 nike

我试图弄清楚,我应该如何正确地为 React 组件状态创建 JSON 模型。因为现在我总是使用 Entity Framework 和虚拟属性来连接相关的“表”,所以现在当我想在 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
}
]
}
}

如何有效连接这两个“表”?例如,如果我想过滤 Components ,其CategoryActive

在第二种方法中,我更改了模型以包含组件中的整个类别对象:

..."Components": [
{
"Id": 1,
"Name": "Component1",
"Category": {
"Id": 1,
"Name": "Cat1",
"Active": true
}
},...

这允许我使用filter(a=>a.Category.Active==true)功能非常容易,但问题是当我更改 Categories 之一的属性时,更改不会反射(reflect)到 Components .

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

我需要Categories在单独的数组中,因为它们并不总是被 Components 使用.

最佳答案

您可以使用数据结构轻松聚合数据并过滤事件组件:

  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 始终有一个类别:

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

关于javascript - 在 React 状态中保持更新的对象关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57254045/

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