无法使用新的Normalizr 3.1.0对实体进行非规范化

时间:2017-01-24 12:49:15

标签: javascript normalizr

我正在尝试将用户反规范化为一个完整的对象。我试图遵循文档here。根据我的理解,输入应该是结果值之一,然后提供模式和实体来处理重建对象。但返回的值是一个对象,其键为0,输入值为0。例如{0:44},而不是整个非规范化的用户对象。

userSchemas.js

import { schema } from 'normalizr';

const photos = new schema.Entity('photos')
const phones = new schema.Entity('phones')
const user = new schema.Entity('users', {
    photos: [photos],
    phones: [phones]
})

const usersSchema = new schema.Array(users)

export { usersSchema, user as userSchema }

反规范化

denormalize([user], userSchema, this.props.users.entities)

this.props.users.entities

{
users : { 
         1: {id:1, name: "john", phones:[2]}
        },
photos : {},
phones : {
          2: {id:2, phone: "34234324"}
         }
}

编辑:可以粘贴到http://requirebin.com中的Gist,以显示控制台中的问题

var normalizr = require("normalizr")

const photos = new normalizr.schema.Entity('photos')
const phones = new normalizr.schema.Entity('phones')
const user = new normalizr.schema.Entity('user', {
    photos: [photos],
    phones: [phones]
})

const usersSchema = new normalizr.schema.Array(user)

var users = [
  {id: 1, name: "bob", phones: [{id:3, phone: 45234324},{id:4, phone: 42342432}]},
    {id: 2, name: "will", phones: [{id:3, phone: 45234324},{id:6, phone: 5435345}]},
    {id: 4, name: "sam", phones: [{id:6, phone: 5345353},{id:7, phone: 42342432}]}
]

var normalizedUsers = normalizr.normalize(users, usersSchema)

var denormalizedUser = normalizr.denormalize([2], user, normalizedUsers)

console.log(denormalizedUser)

1 个答案:

答案 0 :(得分:3)

这一行错了:

var denormalizedUser = normalizr.denormalize([2], user, normalizedUsers)

您的第一个参数应该只是2,或者您的第二个参数应该是[ user ]

[编辑]

此外,normalizedUsers应该只是entities,而不是完整的规范化结果。使用normalizedUsers.entities