開發複雜應用時,資料相互引用無可避免。建議盡可能把 state 正規化(normalize),消除嵌套:把所有資料放在一個物件裡,每筆以 ID 為主鍵,彼此引用時透過 ID 查找——把應用的 state 想成一個資料庫。normalizr 就是做這件事的工具:把巢狀 JSON 攤平,方便 Redux 使用。
把這樣的結構:
[{ id: 1, title: 'Some Article', author: { id: 1, name: 'Dan' } },
{ id: 2, title: 'Other Article', author: { id: 1, name: 'Dan' } }]
轉成:
{
result: [1, 2],
entities: {
articles: {
1: { id: 1, title: 'Some Article', author: 1 },
2: { id: 2, title: 'Other Article', author: 1 }
},
users: { 1: { id: 1, name: 'Dan' } }
}
}
原本每個元素糅合了「文章」與「作者」兩個維度,正規化後兩者拆分,僅以 id 關聯。
import { normalize, Schema, arrayOf } from 'normalizr';
var article = new Schema('articles'),
user = new Schema('users'),
collection = new Schema('collections'),
feedSchema, input;
article.define({ author: user, collections: arrayOf(collection) });
collection.define({ curator: user });
feedSchema = { feed: arrayOf(article) };
最完整的範例可直接參考官方測試檔 test/index.js。
不做正規化時,每個 store 都得先知道 API 的各種結構,寫出一堆樣板程式:
switch (action.type) {
case ActionTypes.RECEIVE_USERS:
mergeUsers(action.rawUsers);
break;
case ActionTypes.RECEIVE_ARTICLES:
action.rawArticles.forEach(rawArticle => {
mergeUsers([rawArticle.user]);
mergeUsers(rawArticle.likers);
mergeUsers([rawArticle.primaryCollection.curator]);
rawArticle.collections.forEach(rawCollection => {
mergeUsers(rawCollection.curator);
});
});
UserStore.emitChange();
break;
}
正規化之後,不論 API 結構多複雜,使用者資料總是固定躺在 action.entities.users:
const article = new Schema('articles');
const user = new Schema('users');
article.define({
author: user,
contributors: arrayOf(user),
meta: { likes: arrayOf({ user: user }) }
});
const json = getArticleArray();
const normalized = normalize(json, arrayOf(article));
// store 端只剩這一段
const { action } = payload;
if (action.response && action.response.entities && action.response.entities.users) {
mergeUsers(action.response.entities.users);
UserStore.emitChange();
}
後端常回傳冗餘欄位(例如 typeId 與 type.id 重複),可用 assignEntity 順手清掉:
var options = {
assignEntity: function(obj, key, val) {
obj[key] = val;
delete obj[key + 'Id'];
}
};
mergeIntoEntity 用來把同一實體的多份資料融合。例如同一個人以 author 與 reviewer 身分出現,留下的聯絡方式互補:
var options = {
mergeIntoEntity: function(entityA, entityB, entityKey) {
var key;
for (key in entityB) {
if (!entityB.hasOwnProperty(key)) { continue; }
if (!entityA.hasOwnProperty(key) || isEqual(entityA[key], entityB[key])) {
entityA[key] = entityB[key];
continue;
}
if (isObject(entityA[key]) && isObject(entityB[key])) {
merge(entityA[key], entityB[key]);
continue;
}
console.warn('Unequal data!');
}
}
};
物件沒有 id,或不想用 id 當鍵時,用 idAttribute 指定,甚至傳入函式動態產生:
var article = new Schema('articles', { idAttribute: 'slug' });
function makeSlug(article) {
var posted = article.posted,
title = article.title.toLowerCase().replace(' ', '-');
return [title, posted.year, posted.month, posted.day].join('-');
}
var article = new Schema('articles', { idAttribute: makeSlug });
// -> 'some-article-1983-3-12'
同一個陣列裡混著文章與教程時,用 schemaAttribute 指定用哪個欄位區分;若原始值與 schema 名有出入,也可傳函式加工:
function guessSchema(item) { return item.type + 's'; }
normalize(input, arrayOf(articleOrTutorial, { schemaAttribute: guessSchema }));
// 一層巢狀
article.define({ author: user });
// 多層交叉引用
article.define({ author: user, collections: arrayOf(collection) });
collection.define({ curator: user });
feedSchema = { feed: arrayOf(article) };
// 遞歸:使用者與文章互相引用
user.define({ articles: arrayOf(article) });
article.define({ collections: arrayOf(collection) });
collection.define({ subscribers: arrayOf(user) });
// 直接自我遞歸:父子關係
var user = new Schema('users');
user.define({ parent: user });
同一個 id 在陣列中出現多次時,normalizr 會自動抽取並合併屬性;若屬性值彼此衝突,會印出警告並剔除衝突欄位。
input = [
{ id: 3, name: 'Jo Rowling', books: [{ id: 1, soldWell: true, name: 'Harry Potter' }] },
{ id: 3, name: 'Jo Rowling', books: [{ id: 1, soldWell: false, name: 'Harry Potter' }] }
];
// 結果:books[1].soldWell 保留先出現的 true,並觸發 console.warn
整體來說,normalizr 的價值不只是「攤平」,還順帶去重與壓縮:同一實體被多處引用時只存一份,更新時也只需改一處,各處引用自動同步。