代码之家  ›  专栏  ›  技术社区  ›  Petr Marek

导入服务器状态后的角度通用,@ngrx/store/update reducers action wipes store

  •  0
  • Petr Marek  · 技术社区  · 6 年前

    在SSR模式下的角度通用项目中,在成功将传输状态导入存储后,下一个调度操作 @ngrx/store/update-reducers 打扫商店。实际上有很多 @NGRX/存储/更新还原器 已启动操作(>10)。

    在@ngrx/store devtools(chrome extension)中检查时,错误地显示 @NGRX/存储/更新还原器 仍然充满了数据,但这不是真的,我看到先前在cmp中加载的数据在很快之后消失了(当这个动作触发时)。

    它只在ssr模式下发生,尽管有多个 @NGRX/存储/更新还原器 仍然存在于@ngrx/store devtools in classic中 ng serve

    DEPS: 角度5.2.7, @ngrx/{store,effects,store devtools,路由器存储}5.2.0, 铬66

    1 回复  |  直到 6 年前
        1
  •  0
  •   Pavel Gurecki    5 年前

    通常 @ngrx/store/update-reducers 从延迟加载的功能模块中添加缩减器。因此,我假设在您的情况下,多个功能模块是延迟加载的。

    最可能发生的情况是,在添加延迟加载模块的还原器之前设置传输状态。默认情况下,ngrx将清除所有未分配还原器的状态部分(这在 combineReducers 在调度的每个操作上运行的函数)。

    可能的解决方案:

    1。在根模块中为特征模块分配默认的约化器

    StoreModule.forRoot(initialReducerMap, { initialState: getInitialState })
    
    export function defaultReducer(state) { return state; }
    
    export const initialReducerMap = {
        // this will make sure `feature1` and `feature2` parts are not cleared on next action
        feature1: defaultReducer,
        feature2: defaultReducer
    } as ActionReducerMap<ApplicationState>;
    
    
    export function getInitialState() {
        return {
            feature1: feature1.initialState,
            feature2: feature2.initialState
        };
    }
    

    更多信息 this blog post

    2。为延迟加载的模块手动设置传输的状态部分

    import { ActionReducer, UPDATE } from "@ngrx/store";
    
    let transferedState: any;
    export function stateSetter(reducer: ActionReducer<any>): ActionReducer<any> {
      return function(state: any, action: any) {
        if (action.type === 'SET_ROOT_STATE') {
          transferedState = action.payload;
          return action.payload;
        }
    
        // on "update-reducers" set their initial transfered state
        if (action.type === UPDATE && transferedState && action.features) {
            const features: string[] = (action as any).features;
            const newState = { ...state };
            for (const feature of features) {
                newState[feature] = newState[feature] || transferedState[feature];
            }
            return reducer(newState, action);
        }
    
        return reducer(state, action);
      };
    }
    

    其他

    提及 this github issue