2017-08-07 125 views
1

可能的重複:如何將狀態值存儲爲redux中的鍵值對?

上述可能重複沒有滿足我的需要。

以下爲終極版減速器代碼我用來存儲作爲對象的數組:

case 'ADD_ITEM': 
    return {...state, elements:[...state.elements, action.appElements]} 

其中action.appElements包含:

{id: '9aq05d', width: '100',height: '225'} 

存儲的對象的陣列看起來像:

elements: { 
    0: { 
    id: 9aq05d, 
    width: '100', 
    height: '225', 
    } 
    1: { 
    id: 8lk65f, 
    width: '200', 
    height: '787', 
    } 
} 

但我需要存儲值爲鍵值對如下所示:

其中我需要id作爲鍵

elements: { 
    9aq05d: { 
    id: 9aq05d, 
    width: '100', 
    height: '225', 
    } 
    8lk65f: { 
    id: 8lk65f, 
    width: '200', 
    height: '787', 
    } 
} 

如何將這種鍵值對存儲在REDX存儲..?

在此先感謝..

回答

0

使用對象傳播而不是數組傳播。

case 'ADD_ITEM': 
    return { 
      ...state, 
      elements: { 
      ...state.elements, 
      [action.appElements.id]: action.appElements 
      } 
    } 

但請記住,不保證對象中按鍵的順序。

相關問題