A component author has no way of knowing which state changes a consumer will want to override, but state reducers handle this problem by allowing the parent component to override any state change.

In Short, we want to have a way to override the component's internal state from outside. The reason for that is there maybe some requirements from the users who want to override component internal state for whatever reason.

The state reducer can accomplish this task, so what is state reducer? It is just a fansic name form some smart developers. State reducer is a function which two two params, one is old state, another one is changes going to be happen, return value is the new state.

export type ToggleStateReducer =
(state: ToggleState, changes: Partial<ToggleState>)
=> ToggleState;

So inside toggle.component.ts, we accept an @Input() stateReducer:

  @Input() stateReducer: ToggleStateReducer =
(state, changes) => ({ ...state, ...changes });

Whenenver we need to change toggle component internal state, we call stateReducer:

  setOnState(on: boolean) {
const oldState = { on: this.on };
const newState = this.stateReducer(oldState, { on });
if (oldState !== newState) {
this.on = newState.on;
this.toggled.emit(this.on);
}
}

That's all what we need to for component part. Just make stateReducer as a input, call each time we need to udpate our internal state, we call thought stateReducer to get new state.

So now, from the consumer component, we can control the state update:

// app.component.ts:

  stateReducer = (state: ToggleState, changes: Partial<ToggleState>) => {
if (this.timesClicked > ) {
return state;
}
if (changes.on !== undefined) {
this.timesClicked = this.timesClicked + ;
}
return { ...state, ...changes };
}
<toggle (toggled)="log('toggle', $event)" [stateReducer]="stateReducer">
<ng-template let-on="on" let-fns="fns">
<switch [on]="on" toggler (click)="fns.toggle()">
</switch>
</ng-template>
</toggle>

最新文章

  1. 设置Hyper-V和VMware多个服务之间共存
  2. 关于linux asp.net MVC网站中 httpHandlers配置无效的处理方法
  3. 【Learning Python】【第四章】Python代码结构(一)
  4. 0525Sprint回顾
  5. Bootstrap页面布局11 - BS表单
  6. VS2012和2010 设置framework版本
  7. RecyclerView实现ViewPager效果
  8. ****The Toy of Flandre Scarlet
  9. Qt入门之基础篇 ( 二 ) :Qt项目建立、编译、运行和发布过程解析
  10. pyhton安装pillow问题解决
  11. mui框架中dialog框的实现
  12. python第一百六十九天,第十九周作业
  13. Java+selenium之WebDriver常见特殊情况如iframe/弹窗处理(四)
  14. Unity应用架构设计(2)——使用中介者模式解耦ViewModel之间通信
  15. java框架之Struts2(2)-访问Servlet API及请求数据封装
  16. Math.round(),Math.ceil(),Math.floor()
  17. SQL优化之count(*),count(列)
  18. 浅析Java虚拟机结构与机制[转]
  19. JS框架图
  20. Java基础知识三点

热门文章

  1. Python基础3 函数 变量 递归 -DAY3
  2. [SQL]连续三天有销售额
  3. NETCORE使用DB First
  4. ios7与ios6UI风格区别
  5. 用户管理命令--useradd
  6. day22 02 面向对象的交互
  7. 基于flask的网页聊天室(三)
  8. HDU 2196 Computer(求树上每个点的最长距离)
  9. 如何在开发时用PC端对移动端页面进行调试
  10. Web框架下安全漏洞的测试反思