[React + Mobx] Mobx and React intro: syncing the UI with the app state using observable and observer

本文介绍如何利用MobX库轻松实现React组件的状态管理,通过装饰器将状态与组件关联,实现自动更新和同步,使得应用开发变得更加简单且免去了大量冗余代码。

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')
)

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值