gpt4 book ai didi

javascript - NGRX:创建多个 reducer react 的 "global"操作的正确方法?

转载 作者:行者123 更新时间:2023-11-29 17:37:45 25 4
gpt4 key购买 nike

声明一个“INIT_ACTION”的正确方法是什么ActionReducerMap 可以根据什么使用react?

这是我的代码的示例,我需要所有 3 个缩减器(图像、标签、添加的标签)对单个操作使用react:

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;

这是一个 reducer 示例:

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;

最佳答案

一个 Action 通过所有的 reducer 。因此,如果您只是在所有 3 个 reducer 中为该操作放置一个 case 语句,那么它将命中所有 3 个 case 语句。

如果在 reducer 中没有针对特定操作的 case 语句,则将触发默认的 case 语句,它只返回原始状态,使其保持不变。

这假设您不是延迟加载 reducer 。 reducer 当然只有在加载时才会被触发。

关于javascript - NGRX:创建多个 reducer react 的 "global"操作的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55220219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com