什么是正确的方法来声明“ INIT_ACTION”? ActionReducerMap可以做出反应吗?
这是我的代码如何运行的示例,我需要所有3个reducer(图像,标签,addedTags)来对一个动作做出反应 :
import { ActionReducerMap, createFeatureSelector } from '@ngrx/store';
import * as fromRoot from '../../../store';
import * as fromImages from './image.reducer';
import * as fromTags from './tag.reducer';
import * as fromAddedTags from './added-tag.reducer';
export interface AnalysisState {
images: fromImages.State;
tags: fromTags.State;
addedTags: fromTags.State;
}
export interface State extends fromRoot.State {
analysis: AnalysisState;
}
export const reducers: ActionReducerMap<AnalysisState> = {
images: fromImages.reducer,
tags: fromTags.reducer,
addedTags: fromAddedTags.reducer
};
export const getAnlysisState = createFeatureSelector<AnalysisState>('analysis');
这是一个示例操作文件:
import { Action } from '@ngrx/store';
import { Tag } from '../../models/tag.model';
export const enum AddedTagActionTypes {
ADD_TAG = '[ANALYSIS] - Add Tag'
}
export class AddTag implements Action {
readonly type = AddedTagActionTypes.ADD_TAG;
constructor(public payload: Tag) {}
}
export type AddedTagActions = AddTag;
这是减速器的示例:
import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';
import * as fromAddedTag from '../actions/added-tag.actions';
import { Tag } from '../../models/tag.model';
export interface State extends EntityState<Tag> {}
export const adapter: EntityAdapter<Tag> = createEntityAdapter<Tag>({
selectId: tag => tag.id
});
export const initialState: State = adapter.getInitialState({});
export function reducer(state = initialState, action: fromAddedTag.AddedTagActions): State {
switch (action.type) {
case fromAddedTag.AddedTagActionTypes.ADD_TAG: {
return adapter.addOne(action.payload, state);
}
default: {
return state;
}
}
}
const { selectIds, selectEntities, selectAll, selectTotal } = adapter.getSelectors();
export const getAllAddedTags = selectAll;
答案 0 :(得分:4)
一个动作通过所有减速器。因此,如果您仅在所有3个reducer中都为该动作放置一个case语句,那么它将击中所有3个case语句。
如果reducer中没有针对特定操作的case语句,则将触发默认case语句,该语句仅返回原始状态,而不会对其进行修改。
这假定您不是延迟加载减速器。减速器当然只有在加载时才被触发。