2016-12-03 32 views
0

在我的應用程序狀態中,我有一個團隊數組。刪除數組中的項目還原狀態?

該團隊陣列包含團隊信息和一系列球員。

當應用程序調用/teams時,球員和球隊在服務器上分離並聯合在一起。

我用響應更新狀態。

現在,當我刪除一個播放器時,我更新了服務器。然後回覆給我一個團隊ID和玩家ID。

我的case語句

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

這是一個有缺陷的方法嗎?

回答

2

如果您希望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 
    }; 
+0

我有一個工作解決方案。這是更少的代碼。看起來不錯。除了playersData是未定義的。這將存在於團隊對象內部。你不應該'team.playersData'? –

+1

的確應該。固定。 –

+0

非常酷。我喜歡這段代碼的整潔。很多es6,但它很好,很小。謝謝。 –