简体   繁体   中英

How to use dispatch in order to push an array to reducer state?

My reducer with an array:

const data = [
  [
    '23.9.2020',
    '11:20',
    'annual',
    'Some Data',
    'Some Data',
  ],
  [
    '11.6.2021',
    '13:45',
    'annual',
    'Some Data',
    'Some Data',
  ],
  ]

const dataPushReducer = (state = data, action) => {
  console.log(data)
  switch (action.type) {
    case 'Push':
      return {
        ...state,
        data: [state.data.concat(action.newItem)],
      }

    default:
      return state
  }
}

The dispatch

const newItem = ['SOME DATA', 'SOME DATA', 'SOME DATA', 'SOME DATA', 'ANOTHER DATA']
<button onClick={()=> dispatch(push(newItem)}

Dispatch not working - how to dispatch the action correctly so the new item is added and displayed in my other component as a new array (as shown in reducer)?

Try this const newItem = ['SOME DATA', 'SOME DATA', 'SOME DATA', 'SOME DATA', 'ANOTHER DATA'] <button onClick={()=> dispatch({type:'Push',newItem})

You have created your default state as an array, not an object. So, you must return an array in your reducer.

Try this if you will maintain your state as an array:

case 'Push':
  return [...state, action.newItem];

Or, if you turn your state into an object:

const INITIAL_STATE =  {
  data: [
    [
      '23.9.2020',
      '11:20',
      'annual',
      'Some Data',
      'Some Data',
    ],
    [
      '11.6.2021',
      '13:45',
      'annual',
      'Some Data',
      'Some Data',
    ],
  ]
}

const dataPushReducer = (state = INITIAL_STATE, action) => {
  console.log(data)
  switch (action.type) {
    case 'Push':
      return {
        ...state,
        data: [...state.data, action.newItem],
      }

    default:
      return state
  }
}

PS: If the .concat() function receives an array as parameter, it will extract the items of your array like this:

var array = [["john", 12], ["mary", 16]];
array.concat(["louis", 15]); 
// will results in [["john", 12], ["mary", 16], "louis", 15]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM