Redux Reducer无法删除数组元素 [英] Redux reducer failing to remove array element

查看:128
本文介绍了Redux Reducer无法删除数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试使Reduce减速器正常工作时遇到问题。我是Redux的新手,所以我可能会缺少一些简单的东西,但是我玩了一段时间,无法弄清楚出了什么问题。

I'm having problems trying to get my reducer to work correctly in Redux. I'm new to Redux so I might be missing something simple, but I've played with it for a while and can't figure out what's going wrong.

这里是我的过程:

首先,我定义所需的索引值。登录后,将返回正确的数字...

First I define the index value that I need. When logged, this returns the correct number...

const thisCommentIndex = parseInt(comments.indexOf(comment))



函数调用:



Function Call:

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



操作:



Action:

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



减速器:



Reducer:

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






当我 console.log('删除索引为'+ action.index的注释),它将正确记录action.index,这是我期望的整数。


When I console.log('removing COMMENT with index of ' + action.index), it logs the action.index correctly, the integer I would expect. But the function doesn't remove the element as expected.

奇怪的是,如果我只是简单地传递数组索引,它就可以正常工作(删除数组元素) (我会这样做,但是由于我设置应用程序的方式,在这种情况下将无法使用)。

Strangely, if I simply pass the array index instead, it works fine (removes the array element). (I would just do this, but due to the way I have set up my app it won't work in this case).

我这里缺少什么?

推荐答案

您错过了 +1 。 ..

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

这篇关于Redux Reducer无法删除数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆