在reducers中使用@ ngrx / store和switch语句的问题

时间:2016-08-20 18:45:27

标签: ngrx

我有以下两个 @ ngrx / store redurs:

import {ActionReducer, Action} from '@ngrx/store';
import {UserAccount} from '../shared/models/useraccount.model';

export const SET_CURRENT_USER_ACCOUNT = 'SET_CURRENT_USER_ACCOUNT';
export const UPDATE_CURRENT_USER_ACCOUNT_FIRST_NAME = 'UPDATE_CURRENT_USER_ACCOUNT_FIRST_NAME';

export const currentUserAccountReducer: ActionReducer<UserAccount> = (state: UserAccount, action: Action) => {

  console.log('currentUserAccountReducer:', state, action);

  switch (action.type) {
    case SET_CURRENT_USER_ACCOUNT: {
      return action.payload;
    }
    case UPDATE_CURRENT_USER_ACCOUNT_FIRST_NAME: {
      state.firstName = action.payload;
      return state;
    }
  }
};

export const SET_AUTHENTICATED = 'SET_AUTHENTICATED';
export const SET_UNAUTHENTICATED = 'SET_UNAUTHENTICATED';

export const authenticatedReducer: ActionReducer<boolean> = (state: boolean, action: Action) => {

  console.log('authenticatedReducer:', state, action);

  switch (action.type) {
    case SET_AUTHENTICATED: {
      return true;
    }
    case SET_UNAUTHENTICATED: {
      return false;
    }
  }
};

但是,出于某种原因,当我为第一个reducer发出一个调度(即currentUserAccountReducer)时,它会改变第二个reducer的状态(即authenticatedReducer)......

以下是导致此问题的调度:

this.store.dispatch({type: SET_CURRENT_USER_ACCOUNT, payload: currentUserAccount});

以下是我在imports部分初始化商店的方法:

StoreModule.provideStore(
 {
   currentUserAccount: currentUserAccountReducer,
   authenticated: authenticatedReducer
 })

有人可以提供建议吗?

修改:问题是authenticated结束undefined !!

1 个答案:

答案 0 :(得分:4)

您的Reducer中的switch语句不包含default个案例。您需要添加返回default的{​​{1}}个案例,因为缩减器将被调用所有操作 - 商店无法知道应该为哪个减少器调用特定的操作类型,因此每个调度的操作都会传递给每个reducer。