Redux reducer删除数组元素失败

Redux reducer failing to remove array element

本文关键字:失败 数组元素 删除 reducer Redux      更新时间:2023-09-26

我有问题试图让我的减速器在Redux中正确工作。我是Redux的新手,所以我可能会错过一些简单的东西,但我已经玩了一段时间,不知道出了什么问题。

下面是我的流程:

定义参数:

首先定义所需的索引值。当被记录时,这将返回正确的数字…

const thisCommentIndex = parseInt(comments.indexOf(comment))
函数调用

:

<div onClick={this.props.removeComment.bind(null, thisCommentIndex)}></div>

行动:

export function removeComment(index) {
   return {
      type: 'REMOVE_COMMENT',
      index
   }
}

减速器:

function comments(state = [], action) {
   switch(action.type) {
      case 'REMOVE_COMMENT' :
         console.log('removing comment with index of ' + action.index)
         return [
            ...state.slice(0, action.index), // why isn't this working???
            ...state.slice(action.index)
         ]
      default :
         return state
   }
   return state;
}

当I console.log('removing COMMENT with index of ' + action.index)时,记录动作。索引正确,就是我期望的整数。但是该函数并没有像预期的那样删除元素。

奇怪的是,如果我只是传递数组索引,它工作得很好(删除数组元素)。(我只是这样做,但由于我设置我的应用程序的方式,它不会在这种情况下工作)。

我错过了什么吗?

你少了一个+1

return [
  ...state.slice(0, action.index),
  ...state.slice(action.index + 1) // <--- need to actually skip what you want to remove
]

@Jack是正确的。另一个选择是使用Array.filter代替:

return state.filter( (item, index) => index !== action.index)

您可能对Redux文档中新的Structuring Reducers部分感兴趣。特别是,不可变更新模式页面有一些相关的例子。

如果您想要删除多个项目,那么您可以反向处理您的数组

 for (var i = this.props.items.length -1; i >= 0; --i) {
   if(this.props.items[i]["selected"]) {
     this.props.deleteSelectedItem(i);
   }
 }