如何使用ES6 ...方法将对象添加到数组中?

时间:2016-10-03 09:33:58

标签: reactjs ecmascript-6

我知道如何处理推送方法:

import * as types from '../constants/ActionTypes'

const initialState = {
  designBox: [],

}

import * as types from '../constants/ActionTypes'
const initialState = {
  designBox: [],

}

export default function(state = initialState, action) {
  switch (action.type) {
  case types.CREATE_DESIGN_BOX:
    let newState = Object.assign({}, state);
    newState.designBox.push(action.payload)
    return newState

  default:
    return state
  }
}

但我不知道如何使用...方法

现在我的代码有问题,designBox无法添加对象,
它只有一个项目,因为它只是被新的action.payload

覆盖
import * as types from '../constants/ActionTypes'

const initialState = {
  designBox: [],

}

export default function(state = initialState, action) {
  switch (action.type) {
  // action.payload format -> { width:200,height:300,text:'abc'}
  case types.CREATE_BOX:
    return {
      ...state,
      designBox: [action.payload]
    }
  default:
    return state
  }
}

我怎么能用...方法做到这一点?

3 个答案:

答案 0 :(得分:1)

也传播阵列:

if t > '200'

此外,您的州不需要是一个对象。如果它只包含一个数组,只需将它作为一个数组:

return {
  ...state,
  designBox: [...state.designBox, action.payload]
}

答案 1 :(得分:0)

使用数组析构函数

case types.CREATE_BOX:
    return {
      ...state,
      designBox: [...state.designBox,action.payload]
    }

答案 2 :(得分:0)

使用对象扩展无法操纵键,只能完全替换它们。但是,当您覆盖键时,可以引用原始对象:

return {
  ...state,
  designBox: state.designBox.concat(action.payload)
}