为数组中的嵌套对象组成redux reducer

时间:2019-09-13 10:27:33

标签: reactjs react-native redux react-redux

我是Redux的新手,在为我的情况编写有效的减速器时遇到一些困难。

我当前的state看起来像这样

export const userData = {
  userID: '12345678',
  userDetails: {
    firstName: 'Joe',
    surname: 'Bloggs'
  },
  currentGames: [
    {
      gameId: 'G-00000001',
      gameSelections: [
        {
          subgameId: '',
          selection: ''
        }
      ]
    }
  ]
};

我的动作看起来像这样

function selectWinner (gameId, subgameId, selection) {
  return {
    type: SELECT_WINNER,
    gameId,
    subgameId,
    selection
  }
}

目标是能够添加/更新gameSelections数组中的对象。

currentGames数组中也可能有多个对象。

我听说我应该使用.map,但我不确定如何使用。

3 个答案:

答案 0 :(得分:1)

使用.map()遍历对象数组是正确的。看起来您的动作创建者具有所有必需的参数来更新减速器状态。

您的减速器看起来像这样:

const userReducer = (state=userData, action) => {
    switch(action.type){
       case SELECT_WINNER:
            return {
                ...state,
                currentGames: [...state.currentGames].map((game) => {
                     if(game.gameId == action.gameId){
                        return {
                           ...game,
                           gameSelections: [...game.gameSelections].map((gameSelection) => {
                               if(gameSelection.subgameId == action.subgameId){
                                  return {
                                      ...gameSelection,
                                      selection: action.selection
                                  }
                               } else {
                                   return gameSelection
                               }
                           })
                        }
                     } else {
                         return game
                     }
                })
            }
       default:
           return state
    }
}

有点混乱,但是会以深度嵌套的状态完成工作。

答案 1 :(得分:0)

将项目添加到数组:

case'ADD_ITEM':
    return { 
        ...state,
        some_arr: [...state.some_arr, action.payload]
    }

更新数组中的特殊项目:

case 'UPDATE_ITEM':
   return { 
       ...state, 
       some_arr: state. some_arr.map(
           (item, index) => index === specific_index
              ? {...item, ...action.payload}
              : content
       )
    }

答案 2 :(得分:0)

需要深度克隆状态。 有用的链接-https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns

const reducer = (state = userData, action) => {
switch (action.type) {
    case CASENAME:
        return {
            userID: state.userID,
            userDetails: {
                ...state.userdetails
            },
            currentGames: [
                {
                    gameId: action.gameId,
                    gameSelections: [
                        {
                            subgameId: action.subgameId,
                            selection: action.selection
                        }
                    ]
                }
            ]
        };
}

}