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

标签 javascript reactjs normalizr

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

我的 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,以解决像我这样的情况,但我确实找到了这样的解决方案。

最佳答案

正如 issue 中提到的:

Normalizr is never going to be able to generate unique IDs for you. We don't do any memoization or anything internally, as that would be unnecessary for most people.

Your working solution is okay, but will fail if you receive one of these entities again later from another API endpoint.

My recommendation would be to find something that's constant and unique on your entities and use that as something to generate unique IDs from.

然后,正如文档中提到的,您需要设置 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}`
}))

关于javascript - Normalizr - 这是一种为非 ID 实体模型生成 ID 的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52273858/

相关文章:

javascript - Extjs Accordion 项目如何使打开的项目在单击它时不再关闭

javascript - 如何记住javascript中的数组值?

javascript - 在 React 组件类中看不到 props 属性

javascript - Redux normalizr + 处理减少的响应

Javascript流解析xml

javascript - 将 div 背景设置为相机拍摄的照片

javascript - 如何获得一个没有空属性的新数组?

reactjs - Material UI 文本字段无法更改多行的字体大小

javascript - 使用 Normalizr 将非嵌套树标准化为嵌套树

javascript - 重命名 Normalizr 中的结果属性