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')
    );
  • 相关阅读:
    基本数据类型
    运算
    登录程序
    MySQL索引
    内存泄漏排查&CPU负载高排查
    dubbo
    SPI
    缓存,热点key
    Java BigDecimal
    Spring Bean's life
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8285362.html
Copyright © 2011-2022 走看看