Redux
ReduxのStoreデータの正規化は、公式ドキュメントにおていも推奨される。
まずは公式ドキュメントのを丁寧に読む。
Normalizing State Shape
正規化のコンセプト
- 各データは自分自身のテーブルを持つ。posts、comments、usersは並列に配置。
- オブジェクトのIDは、オブジェクト自身の名前が値になる。post1はidの値は、"post1"。
- データ同士はidによるリレーションで示す。authorは、user1というリレーションを持つ。
- テーブルは、idの配列を持つ。["post1", "post2"]
{
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 : ".....",
},
},
allIds : ["comment1", "comment2"]
users : {
byId : {
"user1" : {
username : "user1",
name : "User 1",
},
"user2" : {
username : "user2",
name : "User 2",
},
},
正規化のメリット
- ネストから開放されており、ロジックが複雑にならない。また更新がその箇所のみで済む。
- ID指定のみのシンプルな取得や更新が可能になる。
- 親データの関連するオブジェクトのみ更新すればよいので、UIのレンダリングも最小限で良い。
normalizer
使い方
各テーブル毎にnew schema.Entitiyを定義するだけ。
import { normalize, schema } from 'normalizr';
// Define a users schema
const user = new schema.Entity('users');
// Define your comments schema
const comment = new schema.Entity('comments', {
commenter: user,
});
// Define your article
const article = new schema.Entity('articles', {
author: user,
comments: [comment],
});
const normalizedData = normalize(originalData, article);