zoukankan      html  css  js  c++  java
  • [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')
    )
  • 相关阅读:
    Delphi 与 DirectX 之 DelphiX(28): TDIB.Emboss;
    Delphi 与 DirectX 之 DelphiX(29): TDIB.AddMonoNoise();
    Delphi 与 DirectX 之 DelphiX(33): TDIB.SmoothRotateWrap();
    如何用w.bloggar从桌面发表文章
    可以插入图片了
    在首页可以查看阅读次数了
    .Text的MainFeed.aspx生成RSS的问题
    首页文章显示说明
    欢迎光临博客园
    如果想学习.Net Remoting,请看看MSDN上的一篇文章
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5548285.html
Copyright © 2011-2022 走看看