Jing
Chen(Flux的创建者和传播者之一)建议的一种方法是在API响应到达商店之前对其进行展平。我写了一个小库,它就是这样做的:
[{ 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' } } }}(请注意,没有重复且结构平坦。)
Normalizr 可让您:
- 将实体嵌套在其他实体,对象和数组中
- 组合实体架构以表达任何类型的API响应
- 自动合并具有相同ID的实体(如果它们不同则发出警告)
- 使用自定义ID属性(例如,slug)
要使用它,您需要定义您的实体和嵌套规则,并使用它们来转换JSON:
var normalizr = require('normalizr'), normalize = normalizr.normalize, Schema = normalizr.Schema, arrayOf = normalizr.arrayOf;// First, define a schema:var article = new Schema('articles'), user = new Schema('users'), collection = new Schema('collections');// Define nesting rules:article.define({ author: user, collections: arrayOf(collection)});collection.define({ curator: user});// Usage:// Normalize articlesvar articlesJSON = getArticleArray(), normalized = normalize(articlesJSON, arrayOf(article));// Normalize usersvar usersJSON = getUsersArray(), normalized = normalize(usersJSON, arrayOf(user));// Normalize single articlevar articleJSON = getArticle(), normalized = normalize(articleJSON, article);这使您可以在将任何XHR响应传递给Flux Dispatcher之前对其进行标准化。商店只需要从相应的字典进行更新即可:
// UserStoreUserStore.dispatchToken = AppDispatcher.register(function (payload) { var action = payload.action; switch (action.type) { // you can add any normalized API here since that contains users: case ActionTypes.RECEIVE_ARTICLES: case ActionTypes.RECEIVE_USERS: // Users will always be gathered in action.entities.users mergeInto(_users, action.entities.users); UserStore.emitChange(); break; }});// ArticleStoreAppDispatcher.register(function (payload) { var action = payload.action; switch (action.type) { // you can add any normalized API here since that contains articles: case ActionTypes.RECEIVE_ARTICLES: // Wait for UserStore to digest users AppDispatcher.waitFor([UserStore.dispatchToken]); // Articles will always be gathered in action.entities.articles mergeInto(_articles, action.entities.articles); ArticleStore.emitChange(); break; }});


