2016-11-07 6 views
0

友達の連絡先アダムと例Reduxの木グループ:Reduxのは:最初の減速に値を追加した後、第2減速機に新しく作成された値を渡し

{ 
    groups: { 
     1: { 
      name: "Friends" 
      contacts: [1] 
     } 
    } 
    contacts: { 
     1: { 
      name: "Adam" 
     } 
    } 
} 

私が作成したいです新しい友達群で接触し、その結果は次のようなものになるだろう:

{ 
    groups: { 
     1: { 
      name: "Friends" 
      contacts: [1, 2] 
     } 
    } 
    contacts: { 
     1: { 
      name: "Adam" 
     }, 
     2: { 
      name: "Bethany" 
     } 
    } 
} 

現在、両方のレデューサーでreduxアクションを実行する前に、新しい連絡先IDを作成しています。しかし、これは本当に乱雑に感じる、これを行うに行く良い方法がありますか?私の現在のコードは以下の通りです:

contact.js

import { connect } from 'react-redux'; 

function Contact({ createContact, groupId, newContactId }) { 
    function onContactCreate(name) { 
     createContact(newContactId, groupId, name); 
    } 
    // ... 
} 

const mapStateToProps = (state) => { 
    return { 
     newContactId: state.get('contacts').size + 1 
    }; 
}; 

export function mapDispatchToProps(dispatch) { 
    return { 
     createContact: (newContactId, groupId, name) => dispatch({ 
      type: 'CREATE_CONTACT', 
      newContactId, 
      groupId, 
      name 
     }) 
    }; 
} 

export default connect(mapStateToProps, mapDispatchToProps)(Contact); 

接触-reducer.js

import { fromJS } from 'immutable'; 

const initialState = fromJS({}); 

function contactReducer(state = initialState, action) { 
    switch (action.type) { 
     case 'CREATE_CONTACT': { 
      return state 
       .set(action.id, fromJS({ 
        name: action.name 
       })); 
     } 
     default: 
      return state; 
    } 
} 

export default contactReducer; 

グループreducer.js

import { fromJS } from 'immutable'; 

const initialState = fromJS({}); 

function groupReducer(state = initialState, action) { 
    switch (action.type) { 
     case 'CREATE_CONTACT': { 
      let id = action.groupId; 
      return state 
       .updateIn([id, 'contacts'], (contacts) => contacts.push(action.id)); 
     } 
     default: 
      return state; 
    } 
} 

export default groupReducer; 

答えて

2

実際にアクションをディスパッチする前に、IDを作成する必要があります。 IDは現在の状態に依存してはいけません。タイムトラベルツールまたはRedux Devツールを使用して履歴を編集する場合、同じアクションで別のIDのアイテムが作成される可能性があります。これにより、その後の不正なIDを使用するような操作が行われます。

一般に、オブジェクトのアイデンティティはオブジェクトにバインドされ、別々には作成されません。

+0

私が現在行っているやり方は「良い」ですか? – joshhunt

+0

はい、あなたがやっていることは私にとってはすばらしく思えるようです。 – DDS

+0

もう少し説明できますか?「一般的に、オブジェクトのIDはオブジェクトにバインドされ、別々には作成されません」。私はそれが何を意味するのか本当に理解していない。 – joshhunt

関連する問題