【问题标题】:Normalizr - is it a way to generate IDs for non-ids entity model?Normalizr - 它是一种为非 ID 实体模型生成 ID 的方法吗?
【发布时间】:2019-02-15 20:04:44
【问题描述】:

我正在使用normalizr util 来处理基于非 ids 模型的 API 响应。据我所知,normalizr 通常与 ids 模型一起使用,但也许有某种方法可以“随时随地”生成 id?

我的 API 响应示例:

```

// input data:
const inputData = {
  doctors: [
   {
    name: Jon,
    post: chief
   },
   {
    name: Marta,
    post: nurse
   },
   //....
}

// expected output data:
const outputData = {
  entities: {
   nameCards : {
    uniqueID_0: { id: uniqueID_0, name: Jon, post: uniqueID_3 },
    uniqueID_1: { id: uniqueID_1, name: Marta, post: uniqueID_4 }
   },
   positions: {
    uniqueID_3: { id: uniqueID_3, post: chief },
    uniqueID_4: { id: uniqueID_4, post: nurse }
   }
  },
  result: uniqueID_0
}

```

附: 我从某人那里听说过在normalizr 中为我这样的情况“通过引擎盖”生成ID,但我确实找到了这样的解决方案。

【问题讨论】:

标签: javascript reactjs normalizr


【解决方案1】:

有一个 processStrategy ,它基本上是一个函数,并在该函数中分配你的 id,即。 value.id = uuid()。访问下面的链接以查看示例 https://github.com/paularmstrong/normalizr/issues/256

【讨论】:

    【解决方案2】:

    正如issue中提到的:

    Normalizr 永远无法为您生成唯一 ID。我们 不要在内部做任何记忆或任何事情,因为那将是 对大多数人来说是不必要的。

    您的工作解决方案没问题,但如果您收到其中之一,则会失败 这些实体稍后会再次从另一个 API 端点。

    我的建议是找到一些不变的东西 在您的实体上独一无二,并将其用作生成独特的东西 来自的 ID。

    然后,如文档中所述,您需要设置 idAttribute 以将“id”替换为另一个键:

    const data = { id_str: '123', url: 'https://twitter.com', user: { id_str: '456', name: 'Jimmy' } };
    
    const user = new schema.Entity('users', {}, { idAttribute: 'id_str' });
    const tweet = new schema.Entity('tweets', { user: user }, { 
        idAttribute: 'id_str',
        // Apply everything from entityB over entityA, except for "favorites"
        mergeStrategy: (entityA, entityB) => ({
          ...entityA,
          ...entityB,
          favorites: entityA.favorites
        }),
        // Remove the URL field from the entity
        processStrategy: (entity) => omit(entity, 'url')
    });
    
    const normalizedData = normalize(data, tweet);
    

    编辑

    您始终可以使用外部库或手动提供唯一 ID:

    inputData.doctors = inputData.doctors.map((doc, idx) => ({ 
      ...doc, 
      id: `doctor_${idx}`
    }))
    

    【讨论】:

      猜你喜欢
      • 2017-02-02
      • 2016-07-31
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-13
      相关资源
      最近更新 更多