2

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

3 Answers 3

3

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 = [];
Sign up to request clarification or add additional context in comments.

2 Comments

Is it a common way the initialState is array not object??
If it only has one key which has an array as an value anyway, then there is no reason to nest the stuff you want to access later a level deeper than necessary.
0

Use array destructor

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

Comments

0

There's no way using object spread to manipulate keys, only replace them entirely. You can however refer to the original object when you're overriding keys:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.