zoukankan      html  css  js  c++  java
  • [Mobx] Using mobx to isolate a React component state

    React is great for diffing between Virtual-DOM and rendering it to the dom. It also offers a naïve solution for diffing state in terms of setState. However it is slightly verbose and not easy to scale. MobX offers a very simple and effective solution to manage state in React components.

    The whole to use Mobx is to sprate "Data logic" from 'DOM presentation'. 

    The state can be marked by '@observable'.

    The function to dispatch action can be maked by '@action'.

    The React class can be marked by '@observe'.

    import * as React from 'react';
    import * as ReactDOM from 'react-dom';
    import { observable, action } from 'mobx';
    import { observer } from 'mobx-react';
    
    class HelloData {
      @observable clickedCount = 0;
    
      @action
      increment() {
        this.clickedCount++;
      }
    }
    
    @observer
    class Hello extends React.Component<{}> {
      data = new HelloData();
      render() {
        return (
          <button onClick={() => this.data.increment()}>
            Click count = {this.data.clickedCount}
          </button>
        );
      }
    }
    
    ReactDOM.render(
      <Hello />,
      document.getElementById('root')
    );
  • 相关阅读:
    洛谷P2762 太空飞行计划问题
    网络流24题 gay题报告
    洛谷P1712 区间
    洛谷P2480 古代猪文
    10.9zuoye
    面向对象类编程,计算分数
    请输入验证码优化版
    面向对象式开发程序
    直接选择排序与反转排序
    随机数产生原理
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8285362.html
Copyright © 2011-2022 走看看