簡體   English   中英

如何使用 redux 工具和 creactentityAdapter 進行標准化

[英]how to normalize with redux tool and creactentityAdapter

我使用 redux 工具包來構建反應原生應用程序,我嘗試像這樣標准化我的數據

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",
        },
      ],
    },
]

因為這是寫的,所以postAdapternormalize是相互獨立的。 這里發生的事情是normalize正在嘗試將 map 數據轉換為實體,但最終鍵undefined ,因為它使用了具有undefined值的默認鍵id 此外,您還有一array實體,而不僅僅是一個。

postAdapter然后嘗試在該數據上找到已規范化的selectId 但是postAdapter並沒有查看單個post object - 它查看的是由normalize創建的嵌套數據。 它正在查看數據結構Object { "undefined": Object { "0": Object {...來自您的錯誤。 "undefined":是由錯誤的id屬性引起的, "0":是因為它是一個數組。

你如何正確地寫這個取決於你想要做什么。 這里可能不需要進行normalize 看起來response.data中的likes已經返回了 like 和userstring id,而不是normalizr package 旨在展平的深層嵌套數據。 如果您想使用normalize並讓它正常工作,那么您需要在options參數( 文檔鏈接)上設置idAttribute

const postEntity = new schema.Entity('post', {}, {idAttribute: '_id'});

const normalized = data.map( o => normalize(o, postEntity));

idAttribute也接受function 您可以創建一個可重用的 id 提取器 function ,它使用{_id: string;}從任何 object 中提取_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 提取器 function 也適用於createEntityAdapter

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM