繁体   English   中英

React / Redux-如何渲染/更新深层嵌套状态

[英]React / Redux - how to render/update deeply nested sate

我将从API获得一个深层嵌套的状态-例如:

[{
    "id": 1,
    "text": "test",
    "children": [{
        "id": 1,
        "text": "test",
        "children": [{
            "id": 1,
            "text": "test",
            "children": [{
                "id": 1,
                "text": "test",
                "children": []
            }]
        }]
    }]
}]

(请忽略重复的ID等)

现在是这些要求:

  • 我需要正确渲染

例如

<div>
text
  <div>
   text
  </div>
</div>
  • 我需要能够更新Redux存储内的嵌套状态

  • 此列表可能非常庞大-至少需要3k项(理论上效果很好)

我试过的

一切都没有:

  • 渲染非常复杂(使用parentId)
  • 维护结构很困难(需要展平和展平)->这会花费很多性能

嵌套所有内容:

  • 没有“欺骗”反应->直接操纵状态,更新商店是不可能的

有什么解决方案? 什么是架构

在这里,像不变性助手之类的东西可能对您有用。

const state = [{
    "id": 1,
    "text": "test",
    "children": [{
        "id": 1,
        "text": "test",
        "children": [{
            "id": 1,
            "text": "test",
            "children": [{
                "id": 1,
                "text": "test",
                "children": []
            }]
        }]
    }]
}];

const newState = update(state, { 
    0: { 
      children: { 
        0: {
          children {
            0 : {
              children: {
                0: { 
                  "id": { $set: 2}
                }
              }
            }
          }
        }
      }
   };

return newState;

[{
    "id": 1,
    "text": "test",
    "children": [{
        "id": 1,
        "text": "test",
        "children": [{
            "id": 1,
            "text": "test",
            "children": [{
                "id": 2,
                "text": "test",
                "children": []
            }]
        }]
    }]
}];

这里的0可以替换为payload一些索引; 我在这里只使用了0,因为示例数组中只有1个元素。 但是,这是非常深层的嵌套,因此,正如注释所指出的那样,您可以进行的任何拼合将使更新变得更容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM