我在规范化程序examples中看到它们在结果对象上返回了名称属性“users”:
{
result: { users: [ 1, 2 ] },
entities: {
users: {
'1': { id: 1 },
'2': { id: 2 }
}
}
}
我似乎无法弄清楚如何使用我得到的嵌套api响应来做到这一点。我有一个用户和一个地址缩减器,我试图将规范化响应的结果传递给。
我有一个JSON响应,如下所示:
[
{
id: 1
first_name: First,
last_name: Last,
address: {
data: [
{
id: 1,
address_one: '123 Street Ave',
address_two: '',
city: 'Some City',
state: 'CA',
zip: '1234'
}
]
}
},
{
id: 1
first_name: First,
last_name: Last,
address: {
data: [
{
id: 2,
address_one: '123 Street Ave',
address_two: '',
city: 'Some City',
state: 'CA',
zip: '1234'
},
{
id: 3,
address_one: '321 Avenue Road',
address_two: 'Suite 101',
city: 'Some City',
state: 'CA',
zip: '1234'
}
]
}
}
]
我的架构如下所示:
import { schema } from 'normalizr'
/**
* Addresses
*/
const address = new schema.Entity('addresses');
const arrayOfAddresses = new schema.Array(address);
/**
* User
*/
export const user = new schema.Entity('users', {
addresses: arrayOfAddresses
});
user.define({
addresses: {
data: arrayOfAddresses
}
})
export const arrayOfUsers = new schema.Array(user)
执行:let result = normalize(data, schema.arrayOfUseres)
返回:
{
entities: {
addresses: /* The address data */
users: /* The users with an array of the address ids attached to them*/
},
result: [1, 2]
}
我真正想要的是结果对象同时包含用户和地址:
{
entities: {
addresses: /* The address data */
users: /* The users with an array of the address ids attached to them */
},
result: {
addresses: [1, 2, 3]
users: [1, 2]
}
}
这可能吗?我尝试了几种变体
import * as schema from './schema'
normalize(data, { users: [schema.user], addresses: [schema.address] }
但这只是错误输出并将我的数据返回到结果对象。
答案 0 :(得分:3)
这可能吗?
没有。 result
值始终设置为与每个架构的输入数据的顶部结构相匹配。如果您的输入数据没有第一级密钥addresses
,则无法进行。