亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從嵌套在對象中的數組中刪除對象

從嵌套在對象中的數組中刪除對象

慕容708150 2022-07-08 09:58:35
我開始玩一些 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 的一種折磨。有人可能知道寫它的方法嗎?
查看完整描述

2 回答

?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

使用高度嵌套的對象更改狀態可能很困難,但在這種情況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)) 

   };


查看完整回答
反對 回復 2022-07-08
?
臨摹微笑

TA貢獻1982條經驗 獲得超2個贊

我通過使用 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]]}

                }

            }

        });


查看完整回答
反對 回復 2022-07-08
  • 2 回答
  • 0 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號