2016-02-15 16 views
5

私はredux wth reactjsを使用しています。redux - キーと値のペアを保存および更新する方法

単純なキーと値のペアを保存したいが、レデューサー構文を正しく取得できない。

この場合、各キーと値のペアは外部システムへの接続を保持します。

これは正しい方法ですか?私は初心者であるので、それは謎のビットです。

export default (state = {}, action) => { 
    switch(action.type) { 
    case 'addConnection': 
     return { 
     connections: { 
      ...state.connections, { 
      action.compositeKey: action.connection 
     } 
     } 

    default: 
     return state 
    } 
} 

答えて

5

あなただけ{}の代わり[]とカップルのミスがあり、Object.assignを使用することを忘れ。

const reducer = (state = {}, action) => { 
    switch (action.type) { 
    case 'addConnection': 
     return Object.assign({}, state, { 
     connections: [ 
      ...state.connections, 
      { 
      [actions.compositeKey]: action.connection 
      } 
     ] 
     }); 
    default: 
     return state; 
    } 
} 

export default reducer; 

このようにも表示されていることがわかります。あなたは、この

import Immutable from 'immutable'; 

const reducer = (state = Immutable.Map(), {type, compositeKey, connection}) => { 
    switch (type) { 
    case 'addConnection': 
     return state.set(
     'connections', 
     state.get('connections').concat({ 
      [compositeKey]: connection 
     }) 
    ); 
    default: 
     return state; 
    } 
} 

export default reducer; 
+0

働く可能性がある場合、それは同じことを行いますが、私はそれが

const reducer = (state = {}, {type, compositeKey, connection}) => { switch (type) { case 'addConnection': return Object.assign({}, state, { connections: state.connections.concat({ [compositeKey]: connection }) }); default: return state; } } export default reducer; 

少しよりよい読み込むと思いますか2番目または3番目のオプションは、コンパイル時に "Uncaught ReferenceError:action is not defined"と表示されます。 –

+0

'' action'の破壊に 'type'を割り当てるのを忘れました。彼らは今すぐ良いはずです:) – naomik

1

のようなものをImmutableを使っている。これは、私が使用する

const reducer = (state = {}, {type, compositeKey, connection}) => { 
    switch (type) { 
    case 'addConnection': 
     var newData={}; 
     newData[compositeKey]=connection; 
     return Object.assign({}, state, newData) 
     }); 
    default: 
     return state; 
    } 
} 

export default reducer; 
関連する問題