【问题标题】:How to store state values as key value pair in redux..?如何在redux中将状态值存储为键值对..?
【发布时间】:2018-01-14 10:23:15
【问题描述】:

可能的重复:

以上可能的重复不能满足我的需要。

下面是我用来存储为对象数组的 redux reducer 代码:

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',
  }
} 

如何在redux store中存储这种键值对..?

提前致谢..

【问题讨论】:

    标签: reactjs redux react-redux store key-value


    【解决方案1】:

    使用对象传播而不是数组传播。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多