[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') )
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具