【问题标题】:How to get a reference to the nested entities in normalizr?如何获取对 normalizr 中嵌套实体的引用?
【发布时间】:2017-05-27 21:29:44
【问题描述】:

我正在规范一个 一级 嵌套的批次列表。第一级地块被称为主人,嵌套的地块是奴隶。

// my schema
const lot = new schema.Entity('lots');
const lots = new schema.Array(lot);
lot.define({slaves: lots});

// my data
const list = [
  {
    id: 1,
    name: 'Lot #1',
    slaves: [
      {
        id: 2,
        name: 'Lot #2'
      }
    ]
  }, {
    id: 4,
    name: 'Lot #4',
    slaves: []
  }
];

normalize(list, lots);

我明白了:

{
  entities : {
    lots: {
      '1': {
        id: 1,
        name: 'Lot #1',
        slaves: [2]
      },
      '2': {
        id: 2,
        name: 'Lot #2'
      },
      '4': {
        id: 4,
        name: 'Lot #4',
        slaves: []
      }
    }
  },
  result : [1, 4]
}

这有什么问题。但我想在标准化结果中添加更多内容,但我不知道如何。

  • 在规范化的从属设备上拥有主批次 ID
  • 结果中还有一个从属 ID 数组

所以前面的例子会这样归一化:

{
  entities : {
    lots: {
      '1': {
        id: 1,
        name: 'Lot #1',
        slaves: [2]
      },
      '2': {
        id: 2,
        name: 'Lot #2',
        master: 1
      },
      '4': {
        id: 4,
        name: 'Lot #4',
        slaves: []
      }
    }
  },
  result : {
    masters: [1, 4],
    slaves: [2],
  }
}

normalizr 可以做到这一点吗?

【问题讨论】:

    标签: normalizr


    【解决方案1】:

    在规范化的从属设备上拥有主批次 ID

    这绝对可以使用自定义processEntity 函数。有一个example here。简而言之:

    const processStrategy = (value, parent, key) => ({
      ...value,
      master: key === 'slaves' ? parent.id : undefined
    });
    const lot = new schema.Entity('lots', { processStrategy });
    

    结果中还有一个从属 ID 数组

    这是不可能的。 result 始终依赖于传递给 normalize 的条目模式。

    【讨论】:

    • 感谢您的快速回答!
    猜你喜欢
    • 2018-08-15
    • 2016-05-07
    • 2017-12-16
    • 2018-10-10
    • 2017-11-10
    • 2018-05-27
    • 1970-01-01
    • 2019-07-31
    • 2016-07-16
    相关资源
    最近更新 更多