我有一个reducer并尝试更新statearray中的1个项目。它看起来像这样:
const players = (state = [{name:'John',nrGames:0,nrWins:0},{name:'Ed',nrGames:0,nrWins:0},{name:'Mark',nrGames:0,nrWins:0}], action) => {
switch (action.type) {
case 'ADD_PLAYER':
return [...state,{name:action.name}]
case 'ADD_WIN':
return [...state, action.name == 'bla' ? {nrWins:10} : {} ]
default:
return state;
}
};
export default players;
我试图弄清楚如何更改某个名称的nrWins属性。因此,当使用name ='John'调度ADD_WIN时,如何只更新John对象并使用1更新nrWins属性而不是状态中的其他对象?
答案 0 :(得分:3)
您需要incWinForPlayer
超过玩家,当您找到行动描述的玩家时,创建一个具有更新胜利数量的新玩家。为了便于阅读,我创建了一个名为const incWinForPlayer = (name) => (player) => {
return player.name === name
? {...player, nrWins: player.nrWins + 1}
: player
};
const players = (state, action) => {
switch (action.type) {
case 'ADD_PLAYER':
return [...state, {name: action.name}]
case 'ADD_WIN':
return state.map(incWinForPlayer(action.name));
default:
return state;
}
};
export default players;
的函数。
{{1}}
答案 1 :(得分:0)
“推荐”方法是将切片旧数组切换到新项目,将其与修改后的项目连接,并将其与数组的其余部分连接。
确保您的操作返回整个新项目和您要修改的索引。
类似的东西:
case 'ADD_WIN':
return [
...array.slice(0, action.index),
action.item,
...array.slice(action.index)
];