如何用redux更新state中的1项?

时间:2017-12-17 00:11:36

标签: reactjs redux react-redux

我有一个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属性而不是状态中的其他对象?

2 个答案:

答案 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)
  ];

编辑1:来源https://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html#inserting-and-removing-items-in-arrays