Delete an item from Redux state

后端 未结 5 1696
庸人自扰
庸人自扰 2021-01-30 17:44

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 v

5条回答
  •  情话喂你
    2021-01-30 18:42

    For anyone with a state set as an Object instead of an Array:

    I used reduce() instead of filter() to show another implementation. But ofc, it's up to you how you choose to implement it.

    /*
    //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;
                }, {}), 
            }
    

提交回复
热议问题