[英]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",
},
],
},
]
因為這是寫的,所以postAdapter
和normalize
是相互獨立的。 這里發生的事情是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 和user
的string
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.