2017-10-04 4 views
2

Reduxのベストプラクティスは、あなたのnormalize your state shapeタイピング

は、基本的には、以下のことを意味することをお勧めします状態形状:

const blogPosts = [ 
    { 
     id : "post1", 
     author : {username : "user1", name : "User 1"}, 
     body : "......", 
     comments : [ 
      { 
       id : "comment1", 
       author : {username : "user2", name : "User 2"}, 
       comment : ".....", 
      }, 
      { 
       id : "comment2", 
       author : {username : "user3", name : "User 3"}, 
       comment : ".....", 
      } 
     ]  
    }, 
    { 
     id : "post2", 
     author : {username : "user2", name : "User 2"}, 
     body : "......", 
     comments : [ 
      { 
       id : "comment3", 
       author : {username : "user3", name : "User 3"}, 
       comment : ".....", 
      }, 
      { 
       id : "comment4", 
       author : {username : "user1", name : "User 1"}, 
       comment : ".....", 
      }, 
      { 
       id : "comment5", 
       author : {username : "user3", name : "User 3"}, 
       comment : ".....", 
      } 
     ]  
    } 
    // and repeat many times 
] 

はこのように保存しなければならない:

{ 
    posts : { 
     byId : { 
      "post1" : { 
       id : "post1", 
       author : "user1", 
       body : "......", 
       comments : ["comment1", "comment2"]  
      }, 
      "post2" : { 
       id : "post2", 
       author : "user2", 
       body : "......", 
       comments : ["comment3", "comment4", "comment5"]  
      } 
     } 
     allIds : ["post1", "post2"] 
    }, 
    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"] 
    }, 
    users : { 
     byId : { 
      "user1" : { 
       username : "user1", 
       name : "User 1", 
      } 
      "user2" : { 
       username : "user2", 
       name : "User 2", 
      } 
      "user3" : { 
       username : "user3", 
       name : "User 3", 
      } 
     }, 
     allIds : ["user1", "user2", "user3"] 
    } 
} 

ので、 Keyは一意のIDであり、typescriptは基本的に各キーがプロパティになるようにします(例:comment1,comment2)...

したがって、上記のデータ構造を入力する最も良い方法は何ですか?

答えて

2

キーは文字列であるので、あなたはこのように、オブジェクト型としてあなたのタイプを定義することができます。

interface NormalizedObjects<T> { 
    byId: { [id: string]: T }; 
    allIds: string[]; 
} 

interface ReduxState { 
    posts: NormalizedObjects<Post>; 
    comments: NormalizedObjects<Comment>; 
    users: NormalizedObjects<User>; 
} 
+0

私は最近、同様のソリューションが見つかりましたが、一般的なは、それを行うためのより良い方法です。正確に私が必要なもの、ありがとう! – NSjonas

関連する問題