user2492364 user2492364 - 2 months ago 14
React JSX Question

How to add object into array with ES6 ... method ?

I know how to do with push method:

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


But I don't know how to do with
...
method

Now my code has problem, The designBox can't add objects,

it only has one item, because it just overwritten by new
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
}
}


How can I do this with ... method ??

Answer

Spread the the array as well:

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

Also, your state doesn't need to be an object. If it only contains an array just make it an array:

const initialState = [];