Delete an item from Redux state

2019-03-08 21:21发布

I'm wondering if you could help me with this problem if possible. I am trying to delete an item from the Redux state. I have passed in the ID of the item that the user clicks via action.data into the reducer.

I'm wondering how I can match the action.data with one of the ID's within the Redux state and then remove that object from the array? I am also wondering the best way to then set the new state after the individual object has been removed?

Please see the code below:

export const commentList = (state, action) => {
  switch (action.type) {
    case 'ADD_COMMENT':
      let newComment = { comment: action.data, id: +new Date };
      return state.concat([newComment]);
    case 'DELETE_COMMENT':
      let commentId = action.data;

    default:
      return state || [];
  }
}

2条回答
放荡不羁爱自由
2楼-- · 2019-03-08 21:37

Just filter the comments:

case 'DELETE_COMMENT':
  const commentId = action.data;
  return state.filter(comment => comment.id !== commentId);

This way you won't mutate the original state array, but return a new array without the element, which had the id commentId.

To be more concise:

case 'DELETE_COMMENT':
  return state.filter(({ id }) => id !== action.data);
查看更多
叛逆
3楼-- · 2019-03-08 21:53

You can use Object.assign(target, ...sources) and spread all the items that don't match the action id

case "REMOVE_ITEM": {
  return Object.assign({}, state, {
    items: [...state.items.filter(item => item.id !== action.id)],
  });
}
查看更多
登录 后发表回答