2016-03-07 35 views
2

我剛剛開始使用normalizr和Redux,而且我被困在對我來說似乎是一個簡單問題的東西上,但我可能會做這個錯誤。所以我想正常化像這樣的數組:使用normalizr規範化簡單數組

{ 
    articles: [ 
    {id: 1, someValue: 'test'}, 
    {id: 2, someValue: 'test2'} 
    ] 
} 

成這樣的結構:

{ 
    result: { 
    articles: [1,2] 
    }, 
    entities: { 
    articles: { 
     1: {someValue: 'test'}, 
     2: {someValue: 'test2'} 
    } 
    } 
} 

我也試着這樣做:

const article = new Schema('articles'); 
responce = normalize(responce, { 
    articles: arrayOf(article) 
}); 

但是,這給了我一個結構看起來像這樣:

{ 
    articles: { 
    entities: {}, 
    result: { 
     0: {someValue: 'test'}, 
     1: {someValue: 'test2'} 
    } 
    } 
} 

現在沒有文章ID的數組。我假設我在這裏失去了一些東西:

article.define({ 
    ... 
}); 

但找不出什麼需要去那裏在這個簡單的例子

回答

2

你不必定義文章。確保您已正確導入normalizr中的所有內容。我想你的代碼,它給了我預期的結果:

import { normalize, Schema, arrayOf } from 'normalizr'; 

let response = { 
    articles: [ 
    { id: 1, someValue: 'test' }, 
    { id: 2, someValue: 'test2' } 
    ] 
}; 

const article = new Schema('articles'); 

response = normalize(response, { 
    articles: [article] 
}); 

console.log(response); 

輸出:

{ 
    result: { 
    articles: [1,2] 
    }, 
    entities: { 
    articles: { 
     1: {someValue: 'test'}, 
     2: {someValue: 'test2'} 
    } 
    } 
} 
+0

好吧我的錯。事實證明,我試圖直接處理文章數組而不是使用文章屬性的對象 –