从Redux数组中删除当前数组元素

时间:2018-09-28 14:40:29

标签: reactjs redux react-redux

这是我的减速器

const initialState = {
  pros: [''],
}

export const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case ACTION_ADD_PROS:
      return {
          ...state.pros,
          pros: [...state.pros,  action.payload]
        }

    case ACTION_CHANGE_PROS:
      return update(state, { 
        pros: { 
          [action.index]: {
            $set: action.payload
          }}
      });

    case ACTION_REMOVE_PROS:   

   ???


      return x
    default:
  }
  return state;
};

有人可以帮助我如何从数组中删除当前项目吗? 我已经尝试了很多方法,但是我不明白这里的问题是什么, 我也用了react-addons-update来存储更新

3 个答案:

答案 0 :(得分:4)

我认为Array.prototype.filter是从数组中删除项目的最简单易读的解决方案:

return {
  pros: state.filter((item, index) => index !== action.index)
}

答案 1 :(得分:1)

我认为这应该可以解决问题(尚未测试)

您需要创建数组的副本,删除项目,然后将新数组分配给状态

const initialState = {
pros: [''],
}

export const rootReducer = (state = initialState, action) => {
switch (action.type) {
    case ACTION_ADD_PROS:
    return {
        ...state.pros,
        pros: [...state.pros,  action.payload]
        }

    case ACTION_CHANGE_PROS:
    return update(state, { 
        pros: { 
        [action.index]: {
            $set: action.payload
        }}
    });

    case ACTION_REMOVE_PROS:
    // make a copy of the array
    const newArr = state.pros
    // remove item at index 4
    newArr.splice(newArr.indexOf(action.payload), 1)   

    return update(state, {
           pros: [...newArr]
    })

   //this is the old code that is incorrect
   /* return update(state, { 
        pros: { 
        [action.index]: {
            $set: newArr
        }}
    });/*


    return x
    default:
}
return state;
};

有关array.splice()

的更多信息

请记住:切勿直接编辑状态。状态必须是不变的

编辑:返回方法错误,请尝试此方法 编辑:根据您的评论,我更正了newArr 现在它也应该从数组中删除“当前”值 基本上,您将不需要编辑数组的副本,而是只分配较小的数组

答案 2 :(得分:0)

只需splice而不是slice,只需在索引之前,索引之后的数组,然后返回合并后的数组。

它将保持原始阵列不变

  [
    ...state.pros.slice(0, action.index),
    ...state.pros.slice(action.index + 1)
  ]