2016-02-15 27 views
5

Redux wth reactjs kullanıyorum.redux - anahtar/değer çiftinin saklanması ve güncelleştirilmesi

Basit anahtar/değer çiftlerini depolamak istiyorum ancak redüktör sözdizimini doğru olarak alamıyorum.

Bu durumda, her bir anahtar/değer çifti harici bir sistemle bağlantı kurar.

Bunu yapmanın doğru yolu bu mu? Redux ile başlıyorum, bu yüzden biraz gizemli.

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

    default: 
     return state 
    } 
} 

cevap

5

sadece {} yerine [] ve Object.assign kullanmaya unutmadan ile birkaç hataları var.

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; 

Bu şekilde ifade edilmesine yardımcı olabilir. Eğer, bu

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

çalışabilir eğer aynı şeyi yapar ama

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; 

biraz daha güzel okur düşünüyorum Ya sunduğunuz ikinci veya üçüncü seçenekler, derlemede "Uncanught ReferenceError: action tanımlı değil" yazıyor. –

+0

'action'ın yıkımına' type' atamayı unuttum. Şimdi iyi olmalılar :) – naomik

1

gibi bir şey Immutable kullandığınız bu kullandığım

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;