State as array of objects vs object keyed by id

后端 未结 3 1445
孤城傲影
孤城傲影 2020-12-22 15:49

In the chapter on Designing the State Shape, the docs suggest to keep your state in an object keyed by ID:

Keep every entity in an object stored with

3条回答
  •  难免孤独
    2020-12-22 16:27

    Q1: The simplicity of the reducer is a result of not having to search through the array to find the right entry. Not having to search through the array is the advantage. Selectors and other data accessors may and often do access these items by id. Having to search through the array for each access becomes a performance issue. When your arrays get larger, the performance issue worsens steeply. Also, as your app becomes more complex, showing and filtering data in more places, the issue worsens as well. The combination can be detrimental. By accessing the items by id, the access time changes from O(n) to O(1), which for large n (here array items) makes a huge difference.

    Q2: You can use normalizr to help you with the conversion from API to store. As of normalizr V3.1.0 you can use denormalize to go the other way. That said, Apps are often more consumers than producers of data and as such the conversion to store is usually done more frequently.

    Q3: The issues you'll run into by using an array are not so much issues with the storage convention and/or incompatibilities, but more performance issues.

提交回复
热议问题