javascript - Redux normalizr - 嵌套的 API 响应

标签 javascript reactjs redux normalizr reselect

如何使用 normalizr处理嵌套标准化JSON API通过 { data: ... } 标准的关键响应?

例如书籍

{
    data: {
        title: 'Lord of the Rings',
        pages: 9250,
        publisher: {
            data:  {
                name: 'HarperCollins LLC',
                address: 'Big building next to the river',
                city: 'Amsterdam'
            },
        },
        author: {
            data: {
                name: 'J.R.R Tolkien',
                country: 'UK',
                age: 124,
            }
        }
    }
}   

我将如何设计架构来处理嵌套数据键?

最佳答案

对于响应中的每个实体,您应该创建它自己的架构。

在您的示例中,我们有三个实体 - booksauthors发布者:

// schemas.js
import { Schema } from 'normalizr';

const bookSchema = new Schema('book');
const publisherSchema = new Schema('publisher');
const authorSchema = new Schema('author');

如果某个实体包含嵌套数据,需要规范化,我们需要使用它的模式的define方法。这个方法接受一个带有嵌套规则的对象。

如果我们需要规范化 book 实体的 publisherauthor 属性,我们应该将一个对象传递给具有相同结构的 define 函数作为我们的回应:

// schemas.js
bookSchema.define({
  data: {
    publisher: publisherSchema,
    author: authorSchema
  }
});

现在我们可以规范化我们的响应:

import { normalize } from 'normalizr';
import { bookSchema } from './schemas.js';

const response = {
    data: {
        title: 'Lord of the Rings',
        pages: 9250,
        publisher: {
            data:  {
                name: 'HarperCollins LLC',
                address: 'Big building next to the river',
                city: 'Amsterdam'
            },
        },
        author: {
            data: {
                name: 'J.R.R Tolkien',
                country: 'UK',
                age: 124,
            }
        }
    }
}

const data = normalize(response, bookSchema);

关于javascript - Redux normalizr - 嵌套的 API 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38147224/

相关文章:

javascript - 我可以在我的项目中使用 create-react-app 吗?

javascript - 如何让谷歌地图点击获取位置名称?

javascript - 如何在开发人员模式浏览器(检查)中将数据发送到服务器而不显示它?

reactjs - 页面刷新时 Firebase onAuthStateChange 返回未定义

javascript - 显示像 redux devTool 这样的 React reducer 操作

reactjs - Redux createStore<StoreState> 产生错误 : Expected 4 type arguments, 但得到 1

javascript - meteor ,ClientStorage-TypeError : Cannot read property 'has' of undefined

javascript - 基于 webkit 的浏览器将 json 解释为脚本

reactjs - Apollo graphql 使用 React hooks 进行突变轮询

javascript - 如何按值(value)对产品进行排序?