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')
    );
  • 相关阅读:
    Notes of Daily Scrum Meeting(12.22)
    一个合格的程序员应该读过哪些书
    snprintf vs sprintf
    Centos 关闭图形界面
    oracle selinux 问题
    struct 和typedef struct的区别
    c语言字符串函数
    504. Base 7
    汉诺塔python实现
    VIM字符编码基础知识
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8285362.html
Copyright © 2011-2022 走看看