用normalizr

时间:2018-04-11 06:51:35

标签: reactjs redux normalizr

我需要规范化服务器的响应,以将其保存在redux状态。服务器响应一个这样的数组:

[  
   {  
      "name":"parches",
      "id":1,
      "numberOfbundles":0,
      "subdirectories":[  
         {  
            "name":"satelite",
            "id":2,
            "numberOfbundles":3,
            "subdirectories":[]
         }
      ]
   },
   {  
      "name":"layout",
      "id":3,
      "numberOfbundles":0,
      "subdirectories":[  
         {  
            "name":"clientes",
            "id":4,
            "numberOfbundles":3,
            "subdirectories":[  
               {  
                  "name":"demo",
                  "id":5,
                  "numberOfbundles":3,
                  "subdirectories":[]
               }
            ]
         }
      ]
   }
]

我需要获得这样的规范化数据,以将其保存到状态:

{  
   "entities":{  
      "directories":{  
         "1":{  
            "name":"parches",
            "id":1,
            "numberOfbundles":0,
            "subdirectories":[  
               {  }
            ]
         },
         "2":{  
            "name":"satelite",
            "id":2,
            "numberOfbundles":3,
            "subdirectories":[  ]
         },
         "3":{  
            "name":"layout",
            "id":3,
            "numberOfbundles":0,
            "subdirectories":[  
               {  }
            ]
         },
         "4":{  
            "name":"clientes",
            "id":4,
            "numberOfbundles":3,
            "subdirectories":[  
               {  }
            ]
         },
         "5":{  
            "name":"demo",
            "id":5,
            "numberOfbundles":3,
            "subdirectories":[  ]
         }
      },
   },
   "result":[  
      1,
      2,
      3,
      4,
      5
   ]
}

所有目录和子目录必须位于对象实体/目录中,目录中的id必须位于结果数组中。 我怎么能这样做?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

const directory = new schema.Entity('directories')
directory.define({ subdirectories: [directory] })

normalize(data, [directory])

您可以使用define在架构中创建循环引用。