在使用NgRx Store时,可以通过使用纯函数和高阶函数来避免使用if语句。下面是一种解决方法的示例代码:
export enum ActionTypes {
Increment = '[Counter] Increment',
Decrement = '[Counter] Decrement',
Reset = '[Counter] Reset'
}
export class Increment implements Action {
readonly type = ActionTypes.Increment;
}
export class Decrement implements Action {
readonly type = ActionTypes.Decrement;
}
export class Reset implements Action {
readonly type = ActionTypes.Reset;
}
export type CounterActions = Increment | Decrement | Reset;
import { CounterActions, ActionTypes } from './actions';
export interface CounterState {
count: number;
}
export const initialState: CounterState = {
count: 0
};
export function counterReducer(state = initialState, action: CounterActions): CounterState {
switch (action.type) {
case ActionTypes.Increment:
return { ...state, count: state.count + 1 };
case ActionTypes.Decrement:
return { ...state, count: state.count - 1 };
case ActionTypes.Reset:
return { ...state, count: 0 };
default:
return state;
}
}
import { createSelector, createFeatureSelector } from '@ngrx/store';
import { CounterState } from './reducer';
export const selectCounterState = createFeatureSelector('counter');
export const selectCount = createSelector(
selectCounterState,
(state: CounterState) => state.count
);
import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { Increment, Decrement, Reset } from './actions';
import { selectCount } from './selectors';
@Component({
selector: 'app-counter',
template: `
{{ count$ | async }}
`
})
export class CounterComponent {
count$ = this.store.select(selectCount);
constructor(private store: Store) {}
increment() {
this.store.dispatch(new Increment());
}
decrement() {
this.store.dispatch(new Decrement());
}
reset() {
this.store.dispatch(new Reset());
}
}
通过使用NgRx的action、reducer和selector,可以避免使用if语句来处理状态的变化,从而提高代码的可维护性和可测试性。