[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')
);

 

posted @ 2018-01-15 01:25  Zhentiw  阅读(251)  评论(0编辑  收藏  举报