0

我的架构几乎完全按照我想要的方式设置在 redux 状态,除了我想向 formTemplate 对象添加一个表单 ID 数组。它看起来像这样:

// Normalized Form Templates
{
  1: {
    id: '1',
    isGlobal: true,
    name: 'Form Template Name',
    forms: [1, 2], // This is the line I want to add...but how?
  },
}

// Normalized Forms
{
  1: {
    id: '1',
    createdAt: '2016-12-28T23:30:13.547Z',
    name: 'Form 1',
    parentTemplate: '1',
    pdfs: [1, 2],
  },
  2: {
    id: '2',
    createdAt: '2016-12-28T23:30:13.547Z',
    name: 'Form 2',
    parentTemplate: '1',
    pdfs: [],
  },  
}

这是我的架构

import { schema } from 'normalizr'

const formTemplate = new schema.Entity('formTemplates', {}, {
  processStrategy: value => ({
      id: value.id,
      name: value.attributes.title,
      isGlobal: value.attributes.is_global,
    }),
})

const form = new schema.Entity('forms', {
  pdfs: [pdf],
}, {
  processStrategy: value => ({
    id: value.id,
    createdAt: value.attributes.created_at,
    name: value.attributes.title,
    parentTemplate: value.attributes.form_template_id,
    pdfs: [...value.relationships.documents.data],
  }),
})

const pdf = new schema.Entity('pdfs')

export default {
  data: [form],
  included: [formTemplate],
}

这是我正在规范化的 API 响应示例

{
  "data": [
    {
      "id": "5",
      "type": "provider_forms",
      "attributes": {
        "title": "Form 1",
        "created_at": "2017-01-02T06:00:42.518Z",
        "form_template_id": 1
      },
      "relationships": {
        "form_template": {
          "data": {
            "id": "1",
            "type": "form_templates"
          }
        },
        "documents": {
          "data": [ // some pdf data here ]
        }
      }
    }
  ],
  "included": [
    {
      "id": "1",
      "type": "form_templates",
      "attributes": {
        "title": "Form Template",
        "created_at": "2016-12-29T22:24:36.201Z",
        "updated_at": "2017-01-02T06:00:20.205Z",
        "is_global": true
      },
    }
  ]
}

4

2 回答 2

0

好的,我想出了一个方法来做到这一点。我更改了我的 formTemplate 实体以手动映射它们,如下所示:

const formTemplate = new schema.Entity('formTemplates', {}, {
  processStrategy: (value, parent) => {
    // eslint-disable-next-line eqeqeq
    const childrenForms = parent.data.filter(form => form.attributes.form_template_id == value.id)

    return {
      id: value.id,
      name: value.attributes.title,
      isGlobal: value.attributes.is_global,
      forms: childrenForms.map(form => form.id),
    }
  },
})

于 2017-01-06T21:18:12.160 回答
0

您将无法使用 Normalizr 执行此操作,因为表单模板实体没有返回到表单实体的上​​下文。您的操作/减速器需要处理此问题。

于 2017-01-06T20:01:42.330 回答