0

我是ngrx store 的新手,对逻辑的放置感到困惑,即遍历数组是否应该转到reducer 或组件。我有一个 Item 类型的对象数组,并且必须删除一个项目。在删除一个项目时,我必须删除它在父母的孩子以及它的所有孩子中的引用。

    export class Item {
      id: string;
      message: string;
      children: string[];
    }
    

Item 的 children 属性包含 Item 本身类型的对象的 id

    Items: Item[] = [
     {id: "1", "message": "First Message" , children:["4","5"]},
     {id: "2", "message": "Seccond message" , children:["3"]},
     {id: "3", "message": "First child Message" , children:[]},
     {id: "4", "message": "Second child message" , children:["6"]},
     {id: "5", "message": "third child message" , children:[]},
     {id: "6", "message": "child message" , children:[]},
    ]
    

我必须在发送动作“DeleteItemByID”时从数组中删除一个项目及其对应的子项,例如,如果我要删除 id=4 的项目,它会更新 id="1" 的项目并从其中删除“4”儿童阵列。然后删除操作会删除 id="6" 的项的子项,最后删除 id="4" 的项。

    Items: Item[] = [
     {id: "1", "message": "First Message" , children:["5"]},
     {id: "2", "message": "Second message" , children:["3"]},
     {id: "3", "message": "First child Message" , children:[]},
     {id: "5", "message": "third child message" , children:[]},
    ]
    
    export class DeleteItemByID implements Action {
        readonly type = "DeleteById";
     /**
      * Constructor
      * @param payload The id of the discussion to remove
      */
        constructor(public payload: string) { }
    }
    
    /*App state*/
    export class AppState{
        items: Item[]
    }
    
    /* reducer */
    export function reducer(state: AppState = [], action  ) : AppState{
       switch (action.type) {
            case "DeleteById":
                /* Delete Logic*/
                return {};
            default:
                return state;
    }

帮我找出我应该采取的删除操作的最佳方法。

4

1 回答 1

0

他们的正确答案会因情况而异,

案例 1:- 如果您想在多个位置(即多个组件/服务)重用此删除行为。创建两个不同的操作,即 DeleteChildrenItemById 和 DeleteItemById。

或者

您可以创建一个服务方法,该方法将从数组中删除所需的项目,并将一个全新的数组发送到 reducer 以替换现有的数组,这将帮助您避免在 reducer 中进行复杂的登录。

情况 2 :- 如果仅此组件需要此行为,则在组件中进行删除并将此新数组分派给减速器。

于 2020-06-01T06:15:04.413 回答