【问题标题】:how to normalize with redux tool and creactentityAdapter如何使用 redux 工具和 creactentityAdapter 进行规范化
【发布时间】:2021-05-19 13:35:29
【问题描述】:

我使用 redux 工具包构建 react native 应用程序,我尝试像这样规范化我的数据

const postEntitiy = new schema.Entity('post');

const postAdapter = createEntityAdapter({
  selectId: (post) => post._id,
});
const normalized = normalize(response.data, postEntitiy);

这是我的 resopose.data

Array [
  Object {
    "__v": 5,
    "_id": "6020b367cb94a91c9cd48c34",
    "comments": Array [],
    "date": "2021-02-08T03:43:35.742Z",
    "likes": Array [
      Object {
        "_id": "60216bd341b3744ce4b13bee",
        "user": "601f2d46017c85357800da96",
      },
    ],",
  },
]

这是它抛出的错误

The entity passed to the `selectId` implementation returned undefined., You should probably provide          

您自己的selectId 实现。,

The entity that was passed:, Object {
  "undefined": Object {
    "0": Object {
      "__v": 5,
      "_id": "6020b367cb94a91c9cd48c34",

      "comments": Array [],
      "date": "2021-02-08T03:43:35.742Z",
      "likes": Array [
        Object {
          "_id": "60216bd341b3744ce4b13bee",
          "user": "601f2d46017c85357800da96",
        },
      ],
    },
]

【问题讨论】:

    标签: redux react-redux redux-thunk redux-toolkit


    【解决方案1】:

    正如本文所述,postAdapternormalize 彼此独立。这里发生的事情是normalize 正在尝试将数据映射到实体中,但它最终的键为undefined,因为它使用了id 的默认键,该键具有undefined 值。此外,您还有array 的实体,而不仅仅是一个。

    postAdapter 然后尝试在该数据上找到已标准化的selectId。但是postAdapter 不是查看单个post 对象——它查看的是normalize 创建的嵌套数据。它正在查看您的错误中的数据结构Object { "undefined": Object { "0": Object {..."undefined": 是由错误的id 属性引起的,而"0": 是因为它是一个数组。

    你如何正确地写这个取决于你想要做什么。 normalize 可能在这里并不是真正需要的。看起来response.data 中的likes 已经返回string id 和user,而不是normalizr 包旨在展平的深层嵌套数据。如果您想使用normalize 并让它正常工作,那么您需要在options 参数(docs link)上设置idAttribute

    const postEntity = new schema.Entity('post', {}, {idAttribute: '_id'});
    
    const normalized = data.map( o => normalize(o, postEntity));
    

    idAttribute 也接受function。您可以创建一个可重用的 id 提取器函数,该函数从具有 {_id: string;} 的任何对象中提取 _id 属性。

    const myIdExtractor = (object : {_id: string;}) => object._id;
    
    const postEntity = new schema.Entity('post', {}, {idAttribute: myIdExtractor});
    
    const normalized = data.map( o => normalize(o, postEntity));
    

    同样的 id 提取函数也适用于 createEntityAdapter

    const postAdapter = createEntityAdapter({
      selectId: myIdExtractor,
    });
    

    【讨论】:

      猜你喜欢
      • 2020-07-31
      • 2021-08-13
      • 2016-05-17
      • 2019-03-24
      • 2017-05-28
      • 2021-05-14
      • 1970-01-01
      • 2020-01-04
      • 1970-01-01
      相关资源
      最近更新 更多