为什么用
部分项目里面有大量的类和对象(这些类和对象都是前端处理),通过 Normalizr 将数据处理成关系型数据库,该数据库利用 id 做为索引(加快查询速度),符合数据库范式(增删改查数据不会产生副作用) 大多用在将请求回来的 json 规范化后放入 store 中
处理前的数据:
{"id": "123","author": {"id": "1","name": "Paul"},"title": "My awesome blog post","comments": [{"id": "324","commenter": {"id": "2","name": "Nicole"}}]}
import { normalize, schema } from 'normalizr';// Define a users schemaconst user = new schema.Entity('users');// Define your comments schemaconst comment = new schema.Entity('comments', {commenter: user});// Define your articleconst article = new schema.Entity('articles', {author: user,comments: [comment]});const normalizedData = normalize(originalData, article);
处理后的数据:
{result: "123",entities: {"articles": {"123": {id: "123",author: "1",title: "My awesome blog post",comments: [ "324" ]}},"users": {"1": { "id": "1", "name": "Paul" },"2": { "id": "2", "name": "Nicole" }},"comments": {"324": { id: "324", "commenter": "2" }}}}
数据结果包含两个属性:
- result:顶层 entities 的 id(多个则是 id 数组)
- entities:所有通过 schema 识别出来的字典(默认由 id 组成)
怎么用
Normalizr works by defining schemas and then declaring how these schemas are represented through entities.
