Normalizr - 它是一种为非ID实体模型生成ID的方法吗?

问题描述 投票:0回答:2

我正在使用normalizr util来处理基于非id模型的API响应。据我所知,通常normalizr使用id模型,但也许有一些方法可以“随时随地”生成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
2个回答
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}`
}))

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.