Arrays 在Redux中从数组中删除项

Arrays 在Redux中从数组中删除项,arrays,react-redux,Arrays,React Redux,我是Redux新手,正在寻找从Redux中现有数组中删除JSON对象的方法。我试过几种方法,但都不管用。减速器的代码如下所示: const initialState = {serviceList: [{name: 'Ancestome', connectedAt: '08/03/2020'},{name: '23AndMe', connectedAt: '09/03/2020'},{name: 'Cancer Research UK', connectedAt: '09/03/2020'}]}

我是Redux新手,正在寻找从Redux中现有数组中删除JSON对象的方法。我试过几种方法,但都不管用。减速器的代码如下所示:

const initialState = {serviceList: [{name: 'Ancestome', connectedAt: '08/03/2020'},{name: '23AndMe', connectedAt: '09/03/2020'},{name: 'Cancer Research UK', connectedAt: '09/03/2020'}]}


const serviceReducer = (state = initialState, action) => {
  let serviceList = [...state.serviceList]
  switch (action.type) {

    case DELETE_SERVICE:
        delete serviceList[action.id]

      return {
        ...state,   
        serviceList: serviceList
      };

    default:
      return state
  }
}

export default serviceReducer

但是,如果我删除第一个,那么它将删除第一个和最后一个


我不知道发生了什么,如果有人能提出正确的解决方案,我将不胜感激。谢谢

如果
id
表示
servicesList
中元素的索引,则可以使用数组的
filter
方法删除某些元素

您的删除方法如下所示:

case DELETE_SERVICE:
  delete serviceList[action.id]

  return {
    ...state,   
    serviceList: serviceList.filter((e, index) => index !== action.id)
  };

此代码将筛选索引等于
操作
对象中的
id
的元素。

谢谢大家。我发现我的动画列表视图有问题,而不是reducer本身的问题。问题现在已解决。

id是否表示
serviceList
中元素的索引?是的,'id'表示'serviceList'中项目的索引是的,我也尝试过以这种方式使用筛选器。如果我在reducer文件中打印出“serviceList”,那么我可以看到它工作正常,但由于某种原因,当我调用“Service.js”中的函数“deleteService”时,列表没有相应地更新。您所说的“列表没有相应地更新”是什么意思?更新后列表的新状态是什么?在“service.js”中,我连接到存储并对“this.props.serviceList”执行删除操作。由于某些原因,商店中发生的一切都没有在“this.props.serviceList”中更新。例如,删除第二个条目后,reducer中“serviceList”的大小为1,而“this.props.serviceList.length”的大小为2,这意味着不会删除任何内容。这里一定是出了什么问题,我想不出来。
let newList = serviceList.slice(0, action.id).concat(serviceList.slice(action.id + 1));

     return {
        ...state,   
        serviceList: newList
      };
case DELETE_SERVICE:
  delete serviceList[action.id]

  return {
    ...state,   
    serviceList: serviceList.filter((e, index) => index !== action.id)
  };