我正在使用normalizr获取从Api收到的数据。当我收到列表时,我按预期获得规范化的实体。
但是当我发送更新一个实体的请求时,我只收到一个包裹在数据信封中的实体,而且没有正确处理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 :(得分:1)
如果你收到数组你应该使用arrayOf,否则通过res.data.players [0]
引用object更改此
normalize(response, {players: schema.player} )
为:
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
}