【问题标题】:How to flatten an array before applying arrayOf('schema') in normalizrJS如何在 normalizr JS 中应用数组 Of('schema') 之前展平数组
【发布时间】:2016-06-20 10:04:03
【问题描述】:

假设一个用户收藏了许多猫,当被问及用户的收藏时,api 端点给出了一个猫列表:

const catsList = [{id:1,name:"catA"},{id:2,name:"catB"},{id:3,name:"catC"}];

// ex: GET http://app.com/api/favorites =>  results in following json
{favorites:[{id:2,name:"catB"},{id:3,name:"catC"}]} 
// the result is the list of cats 

//and normalizr schema 
const cats = new Schema('cats');
const favorites = new Schema('favorites');

现在我的问题是,我将如何规范化这些实体,以便得到以下结果,

  entities.favorites=[2,3]; //2 and 3 are cats
  entities.cats=[{id:1,name:"a"},{id:2,name:"b"},{id:3,name:"c"}];

我将如何使用 normalizr 完成此任务?

【问题讨论】:

    标签: javascript normalizr


    【解决方案1】:

    类似

    const cats = new Schema('cats');
    
    const response = {
      favorites: [{
        id: 2,
        name: "catB"
      }, {
        id: 3,
        name: "catC"
      }]
    }
    
    const normalized = normalize(response, {
      favorites: arrayOf(cats)
    })
    

    normalized 的值类似于

    {
      result: {
        favorites: [2, 3]
      },
      entities: {
        cats: {
          2: {
            id: 2,
            name: "catB"
          }, {
            id: 3,
            name: "catC"
          }
        }
      }
    }
    

    normalized.entities 是一个对象而不是一个数组实际上非常重要——否则通过 ID 查询会很慢。

    此时,您可以随意转换此表示。

    【讨论】:

      猜你喜欢
      • 2019-11-19
      • 2018-07-05
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      • 2020-07-04
      • 1970-01-01
      • 2014-05-21
      • 2011-12-14
      相关资源
      最近更新 更多