简体   繁体   中英

React / Redux - how to render/update deeply nested sate

I'll get from the API a deeply nested state - eg:

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

(Please ignore duplicate ids etc)

Now here are the requirements:

  • I need to properly render this

eg

<div>
text
  <div>
   text
  </div>
</div>
  • I need to be able to update the nested state within redux store

  • This list can be huge - like at least 3k items (which theoretically works fine)

What I tried:

Having everything unnested:

  • Rendering is very complicated (with parentId)
  • Maintaining the structure is difficult (need to flatten and unflatten it) -> this costs a lot of performance

Having everything nested:

  • Updating the store is impossible without "cheating" in react -> manipulating the state directly

What can be a solution to this? What should be the architecture

Something like immutability-helper will probably be of use to you here.

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": []
            }]
        }]
    }]
}];

The 0 s here could be replaced with some indexes in your payload ; I just used 0 here as the example arrays all have only 1 element in them. This is quite deeply nested though so as the comments pointed out, any flattening you can do will make the updates easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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