2016-08-01 12 views
2

我正在使用normalizr處理從Api接收的數據。當我收到名單時,我會按預期得到正常化的實體。Normalizr未處理信封中的數據

但是當我發送更新一個實體的請求時,我收到的只是一個包裹在數據信封中的實體,沒有正確處理normalizr。

// Normalize setting 
import { Schema, arrayOf } from 'normalizr' 

export const player = new Schema('players') 
export const arrayOfPlayers = arrayOf(player) 

//This is what I use for normalize 
response => normalize(response, {players: schema.player}) 

而且我喜歡在列表中,只有一名球員隨後接收數據:

{ 
    code: 200, 
    message: '', 
    data: { 
     players: [{ 
      id: 20 
      username: 'Gamer' 
     }] 
    } 
} 

我應該改變檢索玩家作爲標準化的實體?

更新:

API調用的例。

fetch(
    url, 
    { credentials: 'include' } 
) 
    .then(checkStatus) 
    .then(response => response.json()) 
    .then(response => normalize(response, {players: schema.player})) 
    .then(// dispatch redux action) 
    .catch(function (error) { 
    }) 
+0

你能提供一個api調用的例子嗎? – mrtig

+0

未經驗證的猜測:'normalize(response.data,...)'或'normalize(response,{data:{players:...}})'? – Bergi

回答

1

如果接收陣列應該使用arrayOf,否則是指通過res.data.players反對[0]

變化這

​​

到:

1)

normalize(response.data, {players: arrayOf(schema.player) }) 

結果將是

{ 
    entities: { 
     players: { 
      20: { 
       id: 20, 
       username: "Gamer" 
      } 
     } 
    }, 
    result: { 
     players: [ 
      20 
     ] 
    } 
} 

2)

normalize(res.data.players[0], player) 

結果將是

{ 
    entities: { 
     players: { 
      20: { 
       id: 20, 
       username: "Gamer" 
      } 
     } 
    }, 
    result: 20 
} 

webpackbin demo test with other options

+0

謝謝我已經使用瞭解決方案1)有小的變化,也許這是糟糕的api設計。但是我正在尋找的響應是索引0上的對象。 normalize(response [0] .data,{players:arrayOf(schema.player)}) –

+0

問題出在後端端點,現在我可以使用normalize(response。數據,{players:schema.player}) –