• [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')
    );
  • 相关阅读:
    声明式编程和命令式编程的比较
    函数式编程
    读《暗时间》
    动态语言和静态语言的比较
    2013第二次实训
    for惠普2013实习生
    bat的大数据
    android stduio优化
    当move手势太快,降低频率
    ANR没root的时候处理*(转)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8285362.html
Copyright © 2020-2023  润新知