如果您有一个规范化的 redux 存储并为实体使用 id,但还有其他额外的唯一标识符并且也需要使用它们,您会怎么做。
例子
{
entities: {
users: {
1: {
name: 'foo',
id: 1, //unique
uuid: '3d89afe9-6a85-46ed-ac0d-28e10b21d09e' // unique
},
// ...
}
}
}
大部分我正在使用id
属性来查找实体,但有时我只有 uuid
属性(property)。
有没有办法使用更高级的模式来拥有第二个映射 uuid
的字典?至 id
, 使用 es6 Map 有一个由 id
组成的键和 uuid
还是我没想到的其他方式?
以下会很有用:
{
entities: {
users: {
1: {
name: 'foo',
id: 1, //unique
uuid: '3d89afe9-6a85-46ed-ac0d-28e10b21d09e' // unique
},
// ...
}
usersUuidToIdMapping: {
'3d89afe9-6a85-46ed-ac0d-28e10b21d09e': 1
// ...
}
}
}
最好的, 法鲁克
最佳答案
如果要将 uuid
定义为 id,可以在定义实体时在 idAttribute
选项上使用字符串。
new schema.Entity('users', {}, { idAttribute: 'uuid' })
如果您想同时使用两者,idAttribute
可以是具有三个参数的函数 value
、parent
和 key
.
new schema.Entity('users', {}, {
idAttribute: user => user.uuid ? `${user.id}-${user.uuid}` : user.id
})
更多信息在这里:https://github.com/paularmstrong/normalizr/blob/master/docs/api.md#idattribute-usage
关于javascript - 如何在 normalizr 中为同一实体设置多个标识符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48429565/