【问题标题】:Remove an Object from Array which is nested in an Object从嵌套在对象中的数组中删除对象
【发布时间】:2020-08-02 09:12:20
【问题描述】:

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

状态应具有如下形式:

我只想从 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 的一种折磨。有人知道怎么写吗?

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    我通过使用 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]]}
                    }
                }
            });
    
    

    【讨论】:

      【解决方案2】:

      使用高度嵌套的对象更改状态可能很困难,但 mapfilter 函数在这种情况下非常有用

      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)) 
         };
      

      【讨论】:

        猜你喜欢
        • 2021-12-28
        • 2020-12-07
        • 1970-01-01
        • 1970-01-01
        • 2019-11-02
        • 2019-04-30
        • 2021-10-29
        • 1970-01-01
        • 2019-03-07
        相关资源
        最近更新 更多