【问题标题】:Normalizr normalize nested dataNormalizr 规范化嵌套数据
【发布时间】:2018-05-23 08:11:46
【问题描述】:

我有一个如下所示的嵌套数据:

{
  components: [
    guid: "cms-container/c154c79596b3af6326966b0c994e2a934",
    regions: [{
      guid :"r1c154c79596b3af6326966b0c994e2a934",
      components: [{ 
          guid: "cms-markupfile/owg-header.html" },
        { guid: "cms-navmenu/n1503636374400" },
        { guid: "cms-container/c50c451ba72e4b4edab979cf477129215",
          regions: [{
            guid: "r1c50c451ba72e4b4edab979cf477129215",
            components: [{
              guid:"cms-serie/serieDetailRenderer"
            }]
          }]
        },
      ]
    }]
  ]
}

如您所见,这是一个任意嵌套的嵌套结构。 也就是说,在组件数组中也可以有一个区域数组,其中又可以有另一个组件数组。

我正在尝试使用 normalizr 将此结构转换为平面形式,但到目前为止还没有结果。我将不胜感激帮助解决这个问题。

【问题讨论】:

  • 展示你到目前为止所拥有的东西会很有价值,即使它还没有完全正常工作。这将帮助人们为您量身定制他们的答案。即使只是您需要标准化数据的形状也会有所帮助。
  • 这可能需要您调整流程和合并策略。这里有更详细的解释:medium.com/@JustinTRoss/…

标签: javascript reactjs vue.js normalizr


【解决方案1】:

我会尝试这么简单的事情:

import { schema } from 'normalizr'

const schemas = {
    component: new schema.Entity('components'),
    region: new schema.Entity('regions')
}

schemas.component.define({
    regions: [schemas.region]
})
schemas.region.define({
    components: [schemas.component]
})

我害怕循环引用,但值得一试。 如果它不起作用,你能提供你迄今为止所做的吗?

【讨论】:

    【解决方案2】:

    老问题,但答案可能对某人有用。 如果我理解正确,每个组件都包含唯一标识符 (guid) 和可能的区域数组,而每个区域包含唯一标识符 (guid) 和可能的组件数组。如果是这种情况,您会在最外层的组件数组中丢失几个{}。而不是

     {
        components: [
    

    你应该写

    {
    components: [{
    

    最后,而不是

      ]
    }
    

    你应该写

     }]
    }
    

    现在,假设我对您的数据的理解是正确的,并且假设您按照建议进行了更正,您的 normalizr 架构应该如下所示:

    import { schema, normalize } from 'normalizr'
    
    const regionSchema = new schema.Entity(
        'regions', 
        { components: [ componentSchema ] }, 
        { idAttribute: 'guid' }
    )
    
    const componentSchema = new schema.Entity(
        'components', 
        { regions: [ regionSchema ] }, 
        { idAttribute: 'guid' }
    )
        
    

    你应该像这样标准化你的数据

    let data = [{
        guid: "cms-container/c154c79596b3af6326966b0c994e2a934",
        regions: [{
          guid :"r1c154c79596b3af6326966b0c994e2a934",
          components: [{ 
              guid: "cms-markupfile/owg-header.html" },
            { guid: "cms-navmenu/n1503636374400" },
            { guid: "cms-container/c50c451ba72e4b4edab979cf477129215",
              regions: [{
                guid: "r1c50c451ba72e4b4edab979cf477129215",
                components: [{
                  guid:"cms-serie/serieDetailRenderer"
                }]
              }]
            },
          ]
        }]
      }]
    
    let normalizedData = normalize(data, [componentSchema])
    

    【讨论】:

      猜你喜欢
      • 2021-05-22
      • 2016-11-15
      • 2018-04-09
      • 2018-11-26
      • 2018-10-10
      • 2017-12-16
      • 1970-01-01
      • 2018-10-19
      • 2021-10-04
      相关资源
      最近更新 更多