2017-09-08 68 views
3
comments : { 
    byId : { 
     "comment1" : { 
      id : "comment1", 
      author : "user2", 
      comment : ".....", 
     }, 
     "comment2" : { 
      id : "comment2", 
      author : "user3", 
      comment : ".....", 
     }, 
     "comment3" : { 
      id : "comment3", 
      author : "user3", 
      comment : ".....", 
     }, 
     "comment4" : { 
      id : "comment4", 
      author : "user1", 
      comment : ".....", 
     }, 
     "comment5" : { 
      id : "comment5", 
      author : "user3", 
      comment : ".....", 
     }, 
    }, 
    allIds : ["comment1", "comment2", "comment3", "commment4", "comment5"] 
} 

在上面的例子中,我有什麼理由需要包含它api包括它。我認爲這樣你可以更快地計數,你可以排序,但通常我不瞭解是否存在性能問題。爲什麼在規範化狀態下需要所有`ids`數組?

+1

在這情況下需求從何而來?這當然不是JavaScript或React的東西。我不能爲Redux說話。 –

+0

這不是Redux的要求。 – Nit

+2

我在幾個問題中看到它。顯然,這是丹·阿布拉莫夫是怎麼做的本教程:https://egghead.io/lessons/javascript-redux-normalizing-the-state-shape – jonahe

回答

5

這不是唯一的要求Redux的東西,這是一個normalizr的事情。要回答你的問題,JavaScript對象can't be replied upon to retain sort order in certain situations。將ID放在數組中允許您保留規範化之前存在的排序順序。

Quote from co-maintainer of Redux and author of "normalizing state shape section" of Redux docs

至於ID陣列,而JS引擎現在有一個相當標準的過程中物體越過鍵進行迭代,你不應該依賴於定義排序。存儲ID數組可以讓您定義項目的順序。

+2

*「來回答你的問題,JavaScript對象不保證順序屬性出現「。*是的,從ES2015開始,請參閱[此處](http://www.ecma-international.org/ecma-262/8.0/index.html#sec- Ordinownpropertykeys)和[here]( http://www.ecma-international.org/ecma-262/8.0/index.html#sec-enumerate-object-properties)和Oriol的解釋[here](https://stackoverflow.com/a/30919039/157247 )。在ES2015中添加了新的操作,並且按照命令「JSON.stringify」。傳統操作('Object.keys','for-in')不需要。但** JSON **沒有屬性順序。 :-) –

+0

normalizr是在2014年創建的,作出反應的應用程序可以在老的瀏覽器作爲IE 9,列舉當normalizr不返回JSON這樣JSON缺乏財產秩序的不是與此有關,規格不要求尊重排序順序您的數據(這是非常常見的應用程序做出反應),和庫的作者明確指出不可靠的排序順序爲他的推理[這裏](https://stackoverflow.com/questions/42238802/redux-many-to-many -relationship/42257112 noredirect = 1#comment71675068_42257112) 我會改以「不能依靠保留」 –

+0

修正:馬克寫的[正火狀態形狀(http://redux.js.org/ docs/recipes/redurs/NormalizingStateShape.html)doc用於Redux,並且是Redux的創始人之一Dan Abramov,他也創建了Normalizr。 –

相關問題