【问题标题】:Unable to denormalize entity with the new Normalizr 3.1.0无法使用新的 Normalizr 3.1.0 对实体进行非规范化
【发布时间】:2017-06-09 06:41:58
【问题描述】:

我正在尝试将用户非规范化回一个完整的对象。我正在尝试根据文档here 进行关注。据我了解,输入应该是结果值之一,然后您提供架构和实体来处理重建对象。但是,返回的值是一个具有 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 中的要点,在控制台中显示问题

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)

【问题讨论】:

  • this.props.users.entities 的值是多少?我怀疑这可能是你的问题所在。
  • 我已经用 this.props.users.entities 数据更新了 OP
  • 您在denormalize([user],... 中传递的user 是导出的架构吗?因为那应该是规范化的用户,而不是模式。只有第二个参数应该是模式。
  • 所以也许这是问题的一部分。我认为您可以将实体的 id/key 作为input 传递给非规范化,而不是整个对象。 input 可以是一个单独的对象还是它总是需要是一个数组?我只想对单个用户实体进行非规范化。
  • 实体的 ID 应该可以工作。我的问题是:denormalize([user], ... 中的user 是什么。没有它,这个问题就无法回答。

标签: javascript normalizr


【解决方案1】:

这一行是错误的:

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

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

[编辑]

另外,normalizedUsers 应该只是 entities,而不是完整的标准化结果。使用normalizedUsers.entities

【讨论】:

  • 当我在 requirebin 示例中尝试您的修改时,它会在 normalizr var entity = (typeof entityOrId === 'undefined' ? 'undefined' : _typeof(entityOrId)) === 'object' ? entityOrId : entities[this.key][entityOrId]; 的这一行上生成 Uncaught TypeError: Cannot read property '2' of undefined。我之前在自己的代码中尝试过您的建议,结果相同。我不确定为什么它在提供的实体列表中找不到该键,当我控制台记录实体时,它显然就在那里。
  • 已编辑...您只需要传递实体对象,而不是标准化结果。
  • 天哪,这太完美了。你是冠军。感谢您在这方面与我保持一致。
猜你喜欢
  • 2018-10-19
  • 2018-10-10
  • 1970-01-01
  • 2013-03-08
  • 2016-06-10
  • 2016-11-15
  • 2017-12-16
  • 2019-02-21
  • 2013-06-30
相关资源
最近更新 更多