我正在尝试更新这个称为大厅的嵌套状态。这就是“大厅”的样子:
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;
}
}
使用参数引用对象数组中的嵌套级别时,传递参数的正确方法是什么?
这种数据结构也是处理处于状态的数据的最佳方法吗?
答案 0 :(得分:1)
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}