从Redux状态删除项目 [英] Delete an item from Redux state
问题描述
我想知道你是否可以帮我解决这个问题。我想从Redux状态删除一个项目。我已经将用户通过 action.data
点击的项目的ID传递到reducer中。
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.
我想知道如何将 action.data
与Redux状态中的一个ID匹配,然后从数组中删除该对象?我还想知道在删除单个对象后设置新状态的最佳方法吗?
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?
请参阅下面的代码:
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 || [];
}
}
推荐答案
过滤评论:
case 'DELETE_COMMENT':
const commentId = action.data;
return state.filter(comment => comment.id !== commentId);
这样你就不会改变原来的州
数组,但返回一个没有元素的新数组,其元素为 commentId
。
This way you won't mutate the original state
array, but return a new array without the element, which had the id commentId
.
要更多简洁:
case 'DELETE_COMMENT':
return state.filter(({ id }) => id !== action.data);
这篇关于从Redux状态删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!