从阵列中删除多个项目-Redux状态

时间:2020-06-12 06:37:57

标签: arrays reactjs redux react-redux redux-thunk

我正在使用redux开发React应用。我想从数组中删除多个项目。我在我的reducer中编写了以下代码,该代码从数组中删除了一个项目,但是我想删除多个项目。

case DELETE_LINK:  
    let dltLink = state.filter(item => {
            return item._id !== action.data._id

    }) 
    return {
        ...state,
        parentFolderlinks: dltLink
    };

3 个答案:

答案 0 :(得分:1)

似乎您想过滤来自state.parentFolderlinks的链接,说您在action.data.ids中有ID,可以

case DELETE_LINK:
    const parentFolderlinks = state.parentFolderlinks.filter(item => {
            return !action.data.ids.includes(item._id);
    });
    return {
        ...state,
        parentFolderlinks
    };

答案 1 :(得分:1)

您要根据什么条件过滤项目?我假设多个项目不会具有相同的id

在以下示例中,我们以type中的fruit过滤了redux foods状态下的多个项目。

// initial state with all types of foods
const initialState = {
    "foods": [
        {
            name: "apple", 
            type: "fruit"
        }, 
        {
            name: "orange", 
            type: "fruit"
        }, 
        {
            name: "broccoli", 
            type: "vegetable"
        }, 
    ]
}

export default (state = initialState, { type, payload }) => {
    switch (type) {

    // delete multiple items without type fruit
    case DELETE_ITEMS_WITHOUT_TYPE_FRUIT:
        const onlyFruits = state.foods.filter(food => food.type !== "fruit");

        return {
            ...state, 
            foods: onlyFruits
        }
    }
}

答案 2 :(得分:-1)

您可以映射状态,并通过一个函数运行它(如果您想保留或不保留它,我不知道您的逻辑是什么),然后在最后返回数组

const keepThisItem =(item) => {
   return item.keep
}

case DELETE_LINK:
    let itemsToKeep = []  
    let dltLink = state.map(item => {
        if(keepThisItem(item){
            itemsToKeep.push(item)
        }
        return itemsToKeep
    }) 
相关问题