Redux reducer failing to remove array element

亡梦爱人 提交于 2019-12-11 06:56:10

问题


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.

Here is my process:

Define argument:

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

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).

Am I missing something here? Any help appreciated.


回答1:


You're missing a +1...

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



回答2:


@Jack is correct. Another option would be to use Array.filter instead:

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

You might be interested in the new Structuring Reducers section of the Redux docs. In particular, the page on Immutable Update Patterns has some related examples.




回答3:


If you want to remove multiple items, then you could work through your array backwards

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


来源:https://stackoverflow.com/questions/40294652/redux-reducer-failing-to-remove-array-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!