2

我在规范化器示例中看到他们在结果对象上返回了一个名称属性“用户”:

{
  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] }

但这只是出错并将我的数据返回到结果对象中。

4

1 回答 1

4

这可能吗?

否。该result值始终设置为与每个架构的输入数据的顶级结构相匹配。如果您的输入数据没有一级 key addresses,这是不可能的。

于 2017-08-21T20:38:23.717 回答