关键字:
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。