1

例如,我有一个简单的 JSON,如下所示:

{
  "id": "123",
  "author": {
    "id": "1",
    "name": "Paul"
  },
  "title": "My awesome blog post",
  "comments": [
    {
      "id": "324",
      "commenter": {
        "id": "2",
        "name": "Nicole"
      }
    },
    {
      "id": "325",
      "commenter": {
        "id": "3",
        "name": "Alex"
      }
    }
  ]
}

在使用normalizr示例中的模式进行规范化之后

import { normalize, schema } from 'normalizr';

// Define a users schema
const user = new schema.Entity('users');

// Define your comments schema
const comment = new schema.Entity('comments', {
  commenter: user
});

// Define your article 
const article = new schema.Entity('articles', { 
  author: user,
  comments: [ comment ]
});

const normalizedData = normalize(originalData, article);

我会得到这个标准化的 JSON:

{
  result: "123",
  entities: {
    "articles": { 
      "123": { 
        id: "123",
        author: "1",
        title: "My awesome blog post",
        comments: [ "324", "325" ]
      }
    },
    "users": {
      "1": { "id": "1", "name": "Paul" },
      "2": { "id": "2", "name": "Nicole" },
      "3": { "id": "3", "name": "Alex" }
    },
    "comments": {
      "324": { id: "324", "commenter": "2" },
      "325": { id: "325", "commenter": "3" }
    }
  }
}

normalizedData.result中,我将只获得文章 ID。但是如果我需要commentsor的 ID 怎么办users?基本上我可以得到它Object.keys(),可能有没有其他方法,normalizr 可以从 API 为我们提供在标准化步骤中获取这些数据?我找不到任何关于它的API。或者你能建议任何方法来做到这一点,而不是自动?因为Object.keys()不适合我。

4

1 回答 1

1

由于您要规范化的值是article,因此result来自 Normalizr 的值将是文章的 ID。正如您自己建议的那样,如果您需要不同的嵌套实体类型的 ID,则必须使用类似Object.keys(normalizedData.entities.comments)

于 2017-01-12T13:54:06.447 回答