为什么用

部分项目里面有大量的类和对象(这些类和对象都是前端处理),通过 Normalizr 将数据处理成关系型数据库,该数据库利用 id 做为索引(加快查询速度),符合数据库范式(增删改查数据不会产生副作用) 大多用在将请求回来的 json 规范化后放入 store 中

处理前的数据:

  1. {
  2. "id": "123",
  3. "author": {
  4. "id": "1",
  5. "name": "Paul"
  6. },
  7. "title": "My awesome blog post",
  8. "comments": [
  9. {
  10. "id": "324",
  11. "commenter": {
  12. "id": "2",
  13. "name": "Nicole"
  14. }
  15. }
  16. ]
  17. }
  1. import { normalize, schema } from 'normalizr';
  2. // Define a users schema
  3. const user = new schema.Entity('users');
  4. // Define your comments schema
  5. const comment = new schema.Entity('comments', {
  6. commenter: user
  7. });
  8. // Define your article
  9. const article = new schema.Entity('articles', {
  10. author: user,
  11. comments: [comment]
  12. });
  13. const normalizedData = normalize(originalData, article);

处理后的数据:

  1. {
  2. result: "123",
  3. entities: {
  4. "articles": {
  5. "123": {
  6. id: "123",
  7. author: "1",
  8. title: "My awesome blog post",
  9. comments: [ "324" ]
  10. }
  11. },
  12. "users": {
  13. "1": { "id": "1", "name": "Paul" },
  14. "2": { "id": "2", "name": "Nicole" }
  15. },
  16. "comments": {
  17. "324": { id: "324", "commenter": "2" }
  18. }
  19. }
  20. }

数据结果包含两个属性:

  • result:顶层 entities 的 id(多个则是 id 数组)
  • entities:所有通过 schema 识别出来的字典(默认由 id 组成)

    怎么用

    Normalizr works by defining schemas and then declaring how these schemas are represented through entities.

参考资料

  1. 把你的 redux store 组织成数据库的形式
  2. normalizr 官方文档
  3. Normalizing your data with normalizr