[英]How to normalize an array of objects in the flattest way for the Redux?
謹防! 這個問題可能令人困惑並且不相關,因為我對錯誤原因的假設是錯誤的,問題出在減速器上,而不是我表示數據的方式。
因此,問題的正確答案是jpdelatorre的答案,而Joao的答案是關於錯誤本身的。
假設我有來自服務器的JSON響應,它是一組嵌套對象。 如何弄平它以使商店處理盡可能容易? 我試圖使用這樣的normalizr工具:
const imageSchema = new Schema('image', { idAttribute: 'id' });
const tooltipSchema = new Schema('tooltips', { idAttribute: 'id' });
imageSchema.define({
tooltips: arrayOf(tooltipSchema),
});
const initData = data.map(item => normalize(item, imageSchema));
但是我相信我做錯了,因為它沒有太大幫助。 存儲仍然太復雜,因此我需要在reducer中使用一些遞歸的東西來更新狀態。
而且,深層嵌套的狀態也使得使用react-redux connect()
變得非常困難,因為它只進行了比較淺的比較 。
響應的形狀如下:
[
{
"id": 1,
"title": "Partridge",
"tooltips": [
{
"id": 10,
"x": 0.56,
"y": 0.59,
"content": "Jacky"
},
{
"id": 11,
"x": 0.08,
"y": 0.8,
"content": "Sarah"
}
]
},
{
"id": 2,
"title": "The Great Seal of South Australia",
"tooltips": [
{
"id": 20,
"x": 0.77,
"y": 0.74,
"content": "A sheaf of wheat"
},
{
"id": 21,
"x": 0.16,
"y": 0.2,
"content": "A sheep"
}
]
}
]
根據此處的示例,似乎您正在嘗試修改狀態(因此,由於redux的比較淺而使您遇到麻煩的原因)。 狀態應視為不變的,而化簡器中返回的所有內容都應該是全新的對象。 Object.assign
修改第一個參數。
嘗試替換return Object.assign(state, { data: newEntities })
使用return Object.assign({}, state, { data: newEntities })
如果您堅持這一點,則不需要平面數據結構。
const imgSchema = new Schema('image', { idAttribute: 'id'});
const tooltipSchema = new Schema('tooltip');
imgSchema.define({
tooltips: arrayOf(tooltipSchema)
});
const normalizedData = normalize(data, arrayOf(imgSchema));
console.log(normalizedData);
這將給您輸出
{
entities: {
image: {
1: {
id: 1,
title: 'Partride',
tooltips: [10, 11]
},
2: {
id: 2,
title: 'The Great Seal...',
tooltips: [20, 21]
}
},
tooltips: {
10: {
id: 10,
content: 'Jacky',
x: 0.56,
y: 0.59
},
...
}
},
result: [1, 2]
}
然后,您可以將其保存到您的redux存儲中。
您的問題是如何以最扁平的方式為Redux標准化對象數組? 。 我相信這是怎么做的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.