修改选择器上的状态对象

时间:2019-10-17 09:49:56

标签: angular ngrx immer.js

如何从选择器返回树列表,该选择器从商店的平面列表派生而来?

在我的nrgx存储中,我有一个平面对象列表,使用ngrx/selector将平面列表转换为树形列表。我刚刚实现了immer,它现在冻结了商店(很好),但是,选择器现在抛出了ERROR TypeError: Cannot assign to read-only property 'children' of object '[object Object]',因为商店被冻结了。也许我走错了路。

我尝试克隆数组,但是只读属性似乎也被克隆了。我也尝试过克隆子项。

    // ngrx/selector
    export const getAllActionScriptItems = createSelector(featureSelector, state => {
      if (state.items && state.items.length > 0) {
        // Tired cloning the head item.
        const headItem = state.items.find(i => i.isHeader) ;
        const sortedActionScripts = [SortActions(state.items, headItem.id)];

        return sortedActionScripts;
      }
    });


    function SortActions(data: IActionScript[], startingId: string, noActions: boolean = false): IActionScript {


      // Clone the array
      const clonedData = [...data];

      // Tired cloning the top level item
      const topLevelItem = { ...clonedData.find(item => item.id === startingId) };


      const children = GetChildren(clonedData, topLevelItem.id);

      GetChildrensChildren(clonedData, children);

      topLevelItem.children = children;



      return topLevelItem;
    }


    function GetChildren(data: IActionScript[], parentId: string) {

      // return data.filter(item => item.parentId === parentId).sort((a, b) => a.eventPosition - b.eventPosition);
      // Tried cloning the child items
      return [...data.filter(item => item.parentId === parentId).sort((a, b) => a.eventPosition - b.eventPosition)];
    }

    function GetChildrensChildren(data: IActionScript[], children: IActionScript[]) {
      children.forEach(child => {

        // ERROR TypeError: Cannot assign to read only property 'children' of object '[object Object]
        child.children = GetChildren(data, child.id);
        if (child.children && child.children.length > 0) {
          GetChildrensChildren(data, child.children);
        }
      });
    }

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题,通过再次使用immer,我在createSelector函数中产生了一个新状态,在阅读了文档之后,produce删除了只读属性。

  

TypeScript键入会自动从草稿类型中删除只读修饰符,并返回与原始类型匹配的值。 -Here

export const getAllActionScriptItems = createSelector(featureSelector, state => {

  if (state.items && state.items.length > 0) {
    const newState = produce(state, draft => {

      const headItem = draft.items.find(i => i.isHeader);
      const sortedActionScripts = [SortActions(draft.items, headItem.id)];
      draft.items = sortedActionScripts;
    });

    return newState.items.find(i => i.isHeader);
  }
});