2017-08-07 40 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 
      } 
    } 

但请记住,不保证对象中按键的顺序。

相关问题