栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Flux应用程序中处理嵌套的API响应?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Flux应用程序中处理嵌套的API响应?

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;  }});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/595130.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号