我无法在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[]}>());
答案 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'}))
)
);