【问题标题】:Delete multiple item from array - Redux State从数组中删除多个项目 - Redux State
【发布时间】:2020-06-12 06:37:57
【问题描述】:

我正在使用 redux 开发 react 应用程序。我想从数组中删除多个项目。我在减速器中编写了以下代码,从数组中删除单个项目,但我想删除多个项目。

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

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

【问题讨论】:

  • ID 往往表示唯一性(或者它们应该!),因此使用任何特定的 id 可能不允许您从数组中删除多个元素。您能否提供更多关于需要从链接数组中删除的内容的详细信息?

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


【解决方案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
    };

【讨论】:

  • return !action.data.ids.includes(item.id) 会更有效,因为它不必遍历整个 action.data.ids 数组。
【解决方案2】:

您希望根据什么过滤项目?我假设多个项目不会有相同的id

下面的例子展示了我们如何在 redux 中过滤多个项目。在这种情况下,foods 将带有 type 的项目声明为 fruit 并删除其他所有内容。

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

// sample reducer that shows how to delete multiple items 
export default (state = initialState, { type, payload }) => {
    switch (type) {
    
    // delete multiple items that does not have type fruit
    // i.e both brocolli and spinach are removed because they have type vegetable
    case DELETE_ITEMS_WITHOUT_TYPE_FRUIT:
        const onlyFruits = state.foods.filter(food => food.type === "fruit");

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

【讨论】:

    【解决方案3】:

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

    const keepThisItem =(item) => {
       return item.keep
    }
    
    case DELETE_LINK:
        let itemsToKeep = []  
        let dltLink = state.map(item => {
            if(keepThisItem(item){
                itemsToKeep.push(item)
            }
            return itemsToKeep
        }) 
    

    【讨论】:

    • 对于数组的迭代,forEach 方法 I(没有返回)是你想要的。在此处使用 map 将返回要保留的数组数组。也不确定这是否回答了操作问题
    猜你喜欢
    • 2019-02-15
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 2021-08-05
    相关资源
    最近更新 更多