2016-12-03 9 views
0

私のアプリケーション状態で私はチームアレイを持っています。配列redux状態でアイテムを削除していますか?

このチームアレイには、チーム情報と選手の配列が含まれています。

プレーヤーとチームは、サーバー上で切り離され、アプリケーションが/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を与える:あなたが説明に書いたので

私は、IDS、およびないインデックスを使用しますシェイプの状態、アクションデータなど、コードに合わせて調整する必要があります。

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はたくさんありますが、その素晴らしさと最小限度。ありがとう。 –

関連する問題