博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Angular] Expose Angular Component Logic Using State Reducers
阅读量:6976 次
发布时间:2019-06-27

本文共 1788 字,大约阅读时间需要 5 分钟。

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;

 

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
) => { if (this.timesClicked > 3) { return state; } if (changes.on !== undefined) { this.timesClicked = this.timesClicked + 1; } return { ...state, ...changes }; }

 

 

转载地址:http://iiupl.baihongyu.com/

你可能感兴趣的文章
Direct2D (15) : 剪辑
查看>>
WinAPI: 钩子回调函数之 SysMsgFilterProc
查看>>
WinAPI: SetRect 及初始化矩形的几种办法
查看>>
理解 Delphi 的类(十) - 深入方法[23] - 重载
查看>>
《一江春水向东流》之随笔
查看>>
EIGRP OSFP 利用NULL0接口防止路由环路 Loopback Null0接口揭秘
查看>>
ipcs
查看>>
TrayIcon 类 添加系统托盘不显示托盘图标
查看>>
Unity3D 材料
查看>>
ControlButton按钮事件
查看>>
HTTP 缓存
查看>>
Apache2.4+Tomcat7集群搭建
查看>>
Linux内置的审计跟踪工具:last命令
查看>>
Nginx自定义模块编写:根据post参数路由到不同服务器
查看>>
Lamp源码安装
查看>>
Linux0.00内核为什么要自己设置0x80号陷阱门来调用write_char过程?
查看>>
mysql数据库备份、恢复文档
查看>>
在linux上MySQL的三种安装方式
查看>>
cocos2dx 场景的切换
查看>>
Java用for循环Map
查看>>