【问题标题】:Removing multiple objects from Redux state array从 Redux 状态数组中移除多个对象
【发布时间】:2019-01-23 16:37:50
【问题描述】:

我有一个具有以下结构的 Redux 状态:

const initialState = {
  data: [
    'device_groups': [
      {
       'id': '1', 'name': 'group 1',
       'devices': [
         {'id': 11, 'name': 'device 11', 'active': 1}, 
         {'id': 12, 'name': 'device 12', 'active': 1},
         {'id': 13, 'name': 'device 13', 'active': 1}
      ]}, 
      {
       'id': '2', 'name': 'group 2',
       'devices': [
         {'id': 21, 'name': 'device 21', 'active': 1}, 
         {'id': 22, 'name': 'device 22', 'active': 0}
       ]}
    ],
   selectedDevices: [
     {'id': 11, 'name': 'device 11', 'active': 1},
     {'id': 12, 'name': 'device 12', 'active': 1},
     {'id': 21, 'name': 'device 21', 'active': 1},
     {'id': 13, 'name': 'device 13', 'active': 1}
   ]
};

在我的组件中,当我单击一个组时,我想从selectedDevices 数组中删除与单击组中的对象具有相同 ID 的所有对象。在这种情况下,对象 ID 为 11、12、13。

我尝试了几种方法,但似乎我总是使用同一个数组。例如我试过这个:

const handleClickedGroup = (state, action) => {
  const updatedDevices = [...state.data.device_groups[action.groupIndex].devices].slice();
  let updatedSelectedDevices = [...state.selectedDevices].slice();
  let newSelDevices = [];

  for (let i in updatedDevices) {
    const selectedDeviceIndex = findObjectIndex(updatedSelectedDevices, updatedDevices[i], 'id');
    newSelDevices = [
      ...updatedSelectedDevices.slice(0, selectedDeviceIndex),
      ...updatedSelectedDevices.slice(selectedDeviceIndex + 1)
    ];
  }

  return updateObject(state, {selectedDevices: newSelDevices});
}

我尝试了更多的东西,但对我没有任何帮助。有可能吗?

更新

我想我找到了解决办法:

const updatedDevices = [...state.data.device_groups[action.groupIndex].devices].slice();
let updatedSelectedDevices = [...state.selectedDevices].slice();
return updateObject(state, {selectedDevices: updatedSelectedDevices.filter(i => !updatedDevices.some(j => j.id === i.id))});

但是我不确定我是否一成不变地这样做。有人可以确认一下吗?

【问题讨论】:

  • data 是数组还是拼写错误?
  • @Treycos 是的,它是一个数组。
  • 哦,好吧,你编辑的最后一行是我开始写的,没关系。快乐编码
  • .slice() 调用是多余的。当您传播阵列时,您正在创建一个新阵列。您可以删除[...x].slice() 调用,您只需要一个。
  • @RossAllen 是的,忘记了!添加它作为使其工作的尝试之一,担心我现在得到一个新数组并改变原始数组。谢谢! :)

标签: reactjs redux react-redux


【解决方案1】:

最终这对我有用:

const updatedDevices = [...state.data.device_groups[action.groupIndex].devices];
let updatedSelectedDevices = [...state.selectedDevices];
return updateObject(state, {
  selectedDevices: updatedSelectedDevices.filter(i => !updatedDevices.some(j => j.id === i.id))
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    相关资源
    最近更新 更多