无法使用有效负载为ngrx文档中的减速器创建有效状态

时间:2020-03-25 20:05:25

标签: ngrx

我无法在ngrx减速器中更新状态以进行操作loadSuccess

load动作后的状态

{
  dashboard: {
    serverList: null,
    isLoading: true,
    error: 'zero'
  }
}

loadSuccess动作后的状态

{
  dashboard: {
    isLoading: false,
    error: 'zero'
  }
}
const t1 = (state, action) => {
  return ({...state, serverList: action.payload.servers});
};

const reducer = createReducer(initialState,
  on(load, state => ({...state, isLoading: true})),
  on(loadSuccess, (state, {servers}) => ({...state, serverList: servers})),
//  on(loadSuccess, t1)
);



export function dashboardReducer(state: State | undefined, action: Action) {
  return reducer(state, action);
}

当我将on(loadSuccess....行换为t1状态时,它起作用。我实际上检查参数中的对象是什么,并获取我想要的值。但是为什么on(loadSuccess, (state, {servers}) => ({...state, serverList: servers}))失败了?

动作定义

export const load = createAction('[Dashboard Component] Load');
export const loadSuccess = createAction('[Dashboard Component] LoadSuccess', props<{servers: ServerInfo[]}>());

3 个答案:

答案 0 :(得分:0)

您应该分享如何定义loadSuccess动作吗?

看起来您具有payload属性,应将其用作payload.servers

答案 1 :(得分:0)

给定函数的第二个参数包含操作,而不是有效负载。

 on(loadSuccess, (state, {payload}) => ({...state, serverList: payload.servers})),

答案 2 :(得分:0)

我发现问题出自ngrx文档,来自效果的定义。

@Injectable()
export class MovieEffects {

  loadMovies$ = createEffect(() => this.actions$.pipe(
    ofType('[Movies Page] Load Movies'),
    mergeMap(() => this.moviesService.getAll()
      .pipe(
        map(movies => ({ type: '[Movies API] Movies Loaded Success', payload: movies })),
        catchError(() => EMPTY)
      ))
    )
  );

  constructor(
    private actions$: Actions,
    private moviesService: MoviesService
  ) {}
}

此处的操作定义为{ type: '[Movies API] Movies Loaded Success', payload: movies }

更改为直接使用上面的操作export const loadSuccess = createAction('[Dashboard Component] LoadSuccess', props<{servers: ServerInfo[]}>());定义后,就可以使用

loadSomething$ = createEffect(() => this.actions$.pipe(
    ofType(DashboardActions.load),
    mergeMap(() => this.service.getServers().pipe(map(servers => Actions.loadSuccess({serverList: servers})))),
    catchError(() => of({type: '[Dashboard Component] ServerInfo Loaded Error'}))
    )
  );