내 응용 프로그램 상태에는 팀 배열이 있습니다.
이 팀 배열에는 팀 정보와 플레이어 배열이 포함됩니다.
플레이어와 팀은 서버에서 분리되고 앱이를 호출 할 때 함께 결합됩니다 /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를 사용하겠습니다.
그런 다음 응답은 나에게 팀 ID와 플레이어 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
};
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다