如何使用Normalizr定义递归模型的模式

tut*_*tts 12 javascript reactjs redux normalizr

尝试规范化我的有效负载时遇到一些问题,该有效负载包含与使用Normalizr的父类型相同类型的嵌套模式

例如,我有一个初始对象(Menu),它有一个子(Sections),它是一个带有截面的对象数组,可以深入.

{
  id: 123,
  sections: [{
    id: 1,
    sections:[{ id: 4, sections: [ id: 5, sections: [] ] }]
  }, {
    id: 2,
    sections:[]
  }, {
    id: 3,
    sections:[]
  }]
}
Run Code Online (Sandbox Code Playgroud)

我首先创建了一个menu模式,该模式在定义中包含链接到sections模式的部分,这些部分适用于第一次传递,但之后不会处理部分的子节点,因此我在section模式中添加了一个具有相同名称的后续定义(值得一试)但它没有用.

const section = new schema.Entity('sections')

const sections = new schema.Entity('sections', {
  sections: section
})

const menu = new schema.Entity('menu', { 
  sections: [ sections ]
})

section.define({ sections })
Run Code Online (Sandbox Code Playgroud)

我希望最终得到以下对象:

{
  entities: {
    menu: {
      sections: [1, 2, 3]
    },
    sections: [{
      1: { id: 1, sections: [4] },
      2: { id: 2, sections: [] },
      3: { id: 3, sections: [] },
      4: { id: 4, sections: [5] },
      5: { id: 5, sections: [] },
    }]
  }
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*ong 21

你的sections架构应该是一个Array.

const section = new schema.Entity('sections')
const sections = new schema.Array(section);
section.define({ sections });
const menu = new schema.Entity('menu', { sections });
Run Code Online (Sandbox Code Playgroud)

然后,在使用它...

const data = {
  id: 123,
  sections: [{
    id: 1,
    sections:[{ id: 4, sections: [ { id: 5, sections: [] } ] }]
  }, {
    id: 2,
    sections:[]
  }, {
    id: 3,
    sections:[]
  }]
};

normalize(data, menu)
Run Code Online (Sandbox Code Playgroud)

将返回:

{
  "entities": {
    "sections": {
      "1": { "id": 1, "sections": [ 4 ] },
      "2": { "id": 2, "sections": [] }, 
      "3": { "id": 3, "sections": [] },
      "4": { "id": 4, "sections": [ 5 ] },
      "5": { "id": 5, "sections": [] }
    },
    "menu": {
      "123": { "id": 123, "sections": [ 1, 2, 3 ] }
    }
  },
  "result": 123
}
Run Code Online (Sandbox Code Playgroud)