[React + Mobx] Mobx and React intro: syncing the UI with the app state using observable and observer
Applications are driven by state. Many things, like the user interface, should always be consistent with that state.
MobX is a general purpose FRP library that provides the means to derive, for example, a React based user interface automatically from the state and keep it synchronized.
The net result of this approach is that writing applications becomes really straight-forward and boilerplate free.
To synchronize the rendering of the state, we are going to use two functions from MobX. The first one is observable. We use observable to decorate our state to count attributes. We say, "MobX, please track this value, so that you can update observers whenever needed."
Next, we mark our component with the observer decorator from the MobX React package. It simply tells MobX, "This component's rendering can be derived from the relevant observables. Do so whenever needed."
const {observable} = mobx; const {observer} = mobxReact; const {Component} = React; @observer class Counter extends Component{ @observable count = 0; render(){ return( <div> Counter: {this.count} <br/> <button onClick={this.inc}>+</button> <button onClick={this.dec}>-</button> </div> ) } inc = () => { this.count++; } dec = () => { this.count--; } } ReactDOM.render( <Counter />, document.getElementById('app') )
Also spreate the state with the component will also works:
const {observable} = mobx; const {observer} = mobxReact; const {Component} = React; const appState = observable({ count : 0 }); appState.inc = function(){ this.count++; } appState.dec = function(){ this.count--; } @observer class Counter extends Component{ render(){ return( <div> Counter: {this.props.store.count} <br/> <button onClick={this.inc}>+</button> <button onClick={this.dec}>-</button> </div> ) } inc = () => { this.props.store.inc(); } dec = () => { this.props.store.dec(); } } ReactDOM.render( <Counter store={appState}/>, document.getElementById('app') )
相关文章
- App Cleaner & Uninstaller 应用程序卸载清理工具,彻底清除残留文件垃圾!
- 教你做一个自己的App
- 创建uni-app项目
- 2022最新苹果APP上架App Store流程(超详细)
- Spark App 血缘解析方案
- 从react源码角度看React-Hydrate原理
- 《一步步了解iOS APP上架流程,让你的APP顺利进入App Store的大门》
- App自动化测试|原生app元素定位方法
- uni.app图片同比例缩放
- 2018最新苹果APP上架App Store流程(超详细)
- HarmonyOS/OpenHarmony 双击返回与退出App
- iPhone 5 Web App 全屏
- create-react-app中CSS Module不生效的解决办法
- 上传IPA包到App Store
- 如何在自己APP中接入在线客服系统,App接入第三方在线客服系统方法
- Create React App 创建前端项目
- 来了!苹果搜索广告ASA可在中国大陆App Store正式投放啦!快来抓住这波流量红利!
- 1天上线1款APP,1年节约35万,这款产品是如何帮助传统企业转型的?
- APP连接MySQL,实现数据互联互通(app调用mysql)
- App测试技术利用Mysql助力质量保障(app测试mysql)
- App中数据库优势之MySQL(app数据库mysql)
- APP端如何实现连接MySQL数据库(app如何连接mysql)
- 探索App与MySQL的交互之路(app与mysql交互)
- 智能化应用App文件夹Oracle引领未来(app文件夹oracle)
- 下载小说神器使用MYSQL打造高效快捷的APP(MYSQL下载小说app)
- App与Oracle融合,拥抱数据驱动未来(app与oracle)
- 怎么发布打包并发布自己的Android应用(APP)