简单理解ngrx

关键字:state;action;reducer;

# state

export interface ControlState {
  loading?: boolean;
  status: string,
  playList: any[]
}

export const initialState: ControlState = {
  loading: false,
  status: 'play',
  playList: []
};
# action
// 为变量设置独一无二的type。

export enum ControlActionTypes {
  ToggleSong = '[ Control ] ToggleSong',
  ToggleStatus = '[ Control ] ToggleStatus',
  PlayOrder = '[ Control ] PlayOrder',
}

// 上一曲下一曲
export class ToggleSong implements Action {
  readonly type = ControlActionTypes.ToggleSong;
  constructor(public data: any) { }
}

// 播放暂停
export class ToggleStatus implements Action {
  readonly type = ControlActionTypes.ToggleStatus;
  constructor(public data: any) { }
}

// 顺序播放或单曲循环
export class PlayOrder implements Action {
  readonly type = ControlActionTypes.PlayOrder;
  constructor(public data: any) { }
}
# reducer
//reducer这个纯函数传入两个参数(state初始数据,action)
//先判断action.type,再返回一个新的state。即表示更新完状态了。
export function counterReducer(state = initialState, action: Action): number {
  switch (action.type) {
    case ControlActionTypes.ToggleSong:
      console.log(action);
      return { ...state };
    case ControlActionTypes.LoadSongUrlSuccess:
      const { data } = action.payload;
      const musicInfo = state.playList[state.current];
      return {
        ...state,
        src: data[0].url,
        coverUrl: musicInfo.al.picUrl,
        alia: modifyArray(musicInfo.ar),
        name: musicInfo.al.name,
        album: musicInfo.name
      };
    default:
      return state;
  }
}
# 说明
- ngrx与vuex和redux一样,是作为状态管理。
- 状态管理的用处。组件1的某个变量改变要使组件2的某个状态改变。组件1和组件2可以是父子,兄弟,其他关系。
- 用状态管理的话,就不用组件通信传来传去那样麻烦了。

1. 在component.html中,通过一些事件会改变状态。(selectShapeEvent)="selectShapeHandler($event)"
2. 在component.ts中,再通过 this.store.dispatch('里面是action' ) 传给Reducer。
selectShapeHandler(shape: string) {
    this.store.dispatch({
      type: SELECT_SHAPE,
      payload: shape
    });
  }
3. 在reducer纯函数中,传入两个参数。(state初始数据,action)。
4. 在reducer函数内,每一个type就写好一种方法。 
	switch(type) case(方法)this.store.dispatch就能通过type找到相对应的方法)
5. 在方法内部,通过 const { data } = action.payload; 获取到payload的数据。
6. Reducer 就是一个纯函数,接收旧的 state 和 action,返回新的 state。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值