首页 > 解决方案 > 在 React Redux 中更新嵌套状态,语法有什么问题?有没有更好的方法来编写这个减速器?

问题描述

我正在尝试更新这个称为大厅的嵌套状态。这就是“大厅”的样子:

this.props = {
    lobby: [ 
        {
            id: 1,
            game: "Basketball",
            teams: 2,
            description: "Come!",
            filled_slots: 4,
            max_slots: 6,
            location_name: "cherry park",
            zipcode: "96024",
            active: true,
            eventDate: new Date(2018, 8, 20, 18),
            current_players_id: {
                 team1: [
                    1
                 ],
                 team2: [
                    2,
                    3,
                    4
                 ]
            }
        },
    {...},
    {...},
    ]
}

这是我迄今为止为更新团队编写的更新函数,我在 return 语句中的语法上遇到了一些问题,因为我使用的是传递的参数。非常感谢任何帮助或建议!

// Parameters passed to the reducer via action
gameId = 1
newTeams = { // passing newTeams to remove player from teams before adding
         team1: [
            1
         ],
         team2: [
            3,
            4
            ]
        }
 team = 'team2'
 userId = 2


// reducer
export const lobbyListReducer = ( state = intitialState, action = {}) => {
switch(action.type) {
    case JOIN_TEAM: 
        const { gameId, newTeams, team, userId } = action.payload;
        // console.log(action.payload)
        const lobbyIndex = () => {
            return state.lobby.findIndex(lobby => {
                return lobby.id === gameId
            })
        }
        // I have syntax errors below
        return {
            ...state, 
            lobby: [
                ...state.lobby, 
                state.lobby[ lobbyIndex() ]: {
                    ...state.lobby[ lobbyIndex() ],
                    state.lobby[ lobbyIndex() ].current_players_id: { 
                            ...newTeams, 
                            [team]: [ 
                                ...state.lobby[ lobbyIndex() ].current_players_id[team], 
                                userId
                            ] 
                        }
                    }
                }
            ]
        }
    default:
        return state;
}
}

使用参数引用对象数组中的嵌套级别时,传递参数的正确方法是什么?

这种数据结构也是处理状态数据的最佳方式吗?

标签: javascriptarraysobjectreduxreact-redux

解决方案


lobby 是一个数组,不能state.lobby[ lobbyIndex() ]: {用来改变数组中的元素。此外,您不需要在一个语句中更改所有内容。分几步做。首先构建最内层数组,然后构建下一个上层,然后构建下一个,直到获得最终结果。

const lobby = state.lobby[lobbyIndex()]
const newTeam = lobby.current_players_id[team].slice()
newTeam.push(userId)
const newLobby = {...lobby, ...{current_players_id: {...lobby.current_players_id, ...{[team]: newTeam}}}}
return {...state, lobby: newLobby}

推荐阅读