簡體   English   中英

從 Redux 狀態中刪除項目

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM