删除数组 redux 状态的项目?

Deleting items in array redux state?

在我的应用程序状态下,我有一个团队数组。

这个团队数组包含团队信息和一个球员数组。

球员和球队在服务器上解耦并在应用程序调用时加入 /teams

我用响应更新状态。

现在当我删除一个播放器时,我会更新服务器。然后响应给了我一个团队 ID 和玩家 ID。

我的案例陈述

case DELETE_PLAYER_SUCCESS:

  // Copy the state
  const playerDeleteSuccessTeams = [...state.teams];

  // Find the team and remove the player
  playerDeleteSuccessTeams.forEach((team, index) => {
    if (team._id === action.result.tid) {
      playerDeleteSuccessTeams[index].playersData.splice(0, action.result.index);
    }
  });

  return {
    ...state,
    teams: playerDeleteSuccessTeams
  };

这是一种有缺陷的方法吗?

如果您希望 React 组件对更改做出反应,您应该为因删除而更改的所有内容创建一个新对象/数组。

我将使用 ID,而不是索引,因为您在描述中写道:

Then the response gives me a team id and player id

我在猜测形状的状态和动作数据,因此您必须调整它以适合您的代码:

case DELETE_PLAYER_SUCCESS:
  const { tid, pid } = action.result; // tid - team id, pid - player id

  // create a new teams array by mapping the old teams
  const teams = state.teams.map((team) => team._id !== tid ? team : ({ // when the tid is found, return a new team object
    ...team,
    playersData: team.playersData.filter((player) => player._id !== pid) // create a new array using filter to remove the player with the pid
  }));

  return {
    ...state,
    teams // assign the new teams array to the state
  };