redux 如何使用分派将数组推入reducer状态?

ukxgm1gy  于 2022-11-12  发布在  其他
关注(0)|答案(2)|浏览(127)

我的带数组的reducer:

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

"派遣“

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

调度不工作-如何正确地调度操作,使新项目作为新数组添加并显示在我的其他组件中(如reducer中所示)?

vaj7vani

vaj7vani1#

你已经创建了一个数组而不是对象的默认状态,所以你必须在reducer中返回一个数组。
如果要将状态保持为数组,请尝试以下操作:

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

或者,如果将状态转换为对象:

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:如果.concat()函数接收一个数组作为参数,它将提取数组中的项,如下所示:

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

ruarlubt2#

试试这个const newItem =['一些数据','一些数据','一些数据','一些数据','另一个数据']〈button onClick={()=〉dispatch({type:'Push',newItem})

相关问题