[英]Delete an item from Redux state
我想知道如果可能的话,你是否可以帮助我解决这个问题。 我正在尝试从 Redux 状态中删除一个项目。 我已将用户通过action.data
单击的项目的 ID 传入减速器。
我想知道如何将action.data
与 Redux 状态中的 ID 之一匹配,然后从数组中删除该对象? 我还想知道在删除单个对象后设置新状态的最佳方法是什么?
请看下面的代码:
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);
这样你就不会改变原始state
数组,而是返回一个没有元素的新数组,它的 id 为commentId
。
更简洁:
case 'DELETE_COMMENT':
return state.filter(({ id }) => id !== action.data);
您可以使用Object.assign(target, ...sources)
并传播所有与操作 ID 不匹配的项目
case "REMOVE_ITEM": {
return Object.assign({}, state, {
items: [...state.items.filter(item => item.id !== action.id)],
});
}
您可以使用尝试这种方法。
case "REMOVE_ITEM":
return {
...state,
comment: [state.comments.filter(comment => comment.id !== action.id)]
}
对于任何将状态设置为对象而不是数组的人:
我使用 reduce() 而不是 filter() 来展示另一个实现。 但是,这取决于您选择如何实施它。
/*
//Implementation of the actions used:
export const addArticle = payload => {
return { type: ADD_ARTICLE, payload };
};
export const deleteArticle = id => {
return { type: DELETE_ARTICLE, id}
*/
export const commentList = (state, action) => {
switch (action.type) {
case ADD_ARTICLE:
return {
...state,
articles: [...state.articles, action.payload]
};
case DELETE_ARTICLE:
return {
...state,
articles: state.articles.reduce((accum, curr) => {
if (curr.id !== action.id) {
return {...accum, curr};
}
return accum;
}, {}),
}
在我的情况下,过滤器在没有 () 和 {} 的情况下工作,并且状态已更新
case 'DELETE_COMMENT':
return state.filter( id => id !== action.data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.