javascript - 在 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;
}
}
使用参数引用对象数组中的嵌套级别时,传递参数的正确方法是什么?
这种数据结构也是处理状态数据的最佳方式吗?
解决方案
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}
推荐阅读
- swift - CGContext.draw(), CGContext.makeImage() 给我双倍的预期分辨率
- android-studio - 在 Android Studio 中配置导入顺序?
- javascript - 如何在client.js中访问登录表单的输入标签值(名称)
- javascript - 如何在 jsdoc 函数参数中指定 Date 对象?
- python-3.x - Python UDP服务器多次接收/输出每个字符
- c++ - 我可以在没有 Visual Studio 的情况下获得 wxWidgets 吗?
- python - 尝试通过 snakemake 配置文件设置命令行值时出错
- sql - 在 SQL Server 中查找序列号
- cassandra - 如何确定 cassandra 中的逻辑/物理读写?
- python - Python:Selenium 在可用时找不到元素