从嵌套在对象中的数组中删除对象

我开始玩一些 redux,到目前为止我很惊讶。我现在的问题是,我的新 reducer 函数改变了一个状态变量的类型,我不希望这样。

状态应具有如下形式:

http://img3.mukewang.com/62c78f620001879605680693.jpg

我只想从 jsons 数组中删除一个对象:


pseudo:

delete state.items[item_index].jsons[json_to_delete_index]

我最终得到了这个 reducer,它现在将项目状态作为对象而不是数组返回。


case DELETE_JSON:

    const item_index = state.items.findIndex((url) => url.url_id === action.payload.url_id);

    const json_index = state.items[item_index].jsons.findIndex((json) => json.json_id === action.payload.json_id);

    return {

        ...state,

        items: {

            ...state.items,

            [item_index]: {

                ...state.items[item_index],

                jsons:

                    [

                        ...state.items[item_index].jsons.splice(0, json_index),

                        ...state.items[item_index].jsons.splice(json_index + 1)

                    ]

            }

        }

    };

到目前为止,我尝试了各种方法,但是在高度嵌套的对象中更改状态似乎仍然是对 redux 的一种折磨。有人可能知道写它的方法吗?


慕容708150
浏览 170回答 2
2回答

幕布斯6054654

使用高度嵌套的对象更改状态可能很困难,但在这种情况map下filter函数确实很有帮助const item_index = state.items.findIndex((url) => url.url_id === action.payload.url_id);const json_index = state.items[item_index].jsons.findIndex((json) => json.json_id === action.payload.json_id);return {    ...state,    items: state.items.map((item, index) => (index === item_index ?    { ...item, item.jsons.filter((json, i) => (i !== json_index)) } : item))    };

临摹微笑

我通过使用 immutability-helpers 的 update() 解决了这个问题。非常便利import update from 'immutability-helper';/* some other code */case DELETE_JSON:    const item_index = state.items.findIndex((url) => url.url_id === action.payload.url_id);    const json_index = state.items[item_index].jsons.findIndex((json) => json.json_id === action.payload.json_id);    return update(state, {            items: {                [item_index]: {                    jsons: {$splice: [[json_index]]}                }            }        });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript