gpt4 book ai didi

javascript - 在 React Redux 中更新嵌套状态,语法有什么问题?有没有更好的方法来编写这个 reducer ?

转载 作者:行者123 更新时间:2023-11-30 20:14:26 25 4
gpt4 key购买 nike

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

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
]
}
},
{...},
{...},
]
}

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

// 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;
}
}

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

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

最佳答案

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}

关于javascript - 在 React Redux 中更新嵌套状态,语法有什么问题?有没有更好的方法来编写这个 reducer ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52067042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com