mobx 的基本使用

406 阅读1分钟

简介

cn.mobx.js.org/

使用

  1. react app 创建
npx create-react-app myapp

cd myapp

yarn start

  1. 组件包安装

yarn add mobx mobx-react

注意: mobx 的使用需要使用装饰器模式,则需要开启 react 的装饰器模式

https://www.npmjs.com/package/customize-cra
  1. 仓库 store.js 建立

import { observable,action, computed } from "mobx";

class CounterStore {

	name = 'Counter App';

	@observable count = 100;

 	@computed get doubleCount() {
        return this.count * 2;
    }

	@action.bound increment() {
        this.count += 1; // 'this' 永远都是正确的
    }



    @action.bound decrement() {
        this.count -= 1; // 'this' 永远都是正确的
    }


}

export default new CounterStore();

  1. App.js 实例化调用
import React, { Component } from 'react';

import store from './store.js'
import {observer} from "mobx-react";

import Show from './Show.js'

// 订阅数据仓库

@observer
class App extends Component {
     
      clickHandler = ()=> {
      console.log('click');
      store.increment();
      console.log( store );

    }

      render() {
        return (
          
         <div>
            <button onClick={store.decrement}>-</button>
          <p>{store.count}</p>  
          <Show store={store}></Show>
          <button onClick={this.clickHandler}>+</button>  
         </div>
         )
           
    
      }
    }

export default App;

  1. 其他组件使用仓库数据
import React from 'react';
import ReactDom from 'react-dom';
import {observer} from "mobx-react";

@observer
class Show extends React.Component{
	render(){
		console.log( this.props );
		return (
				<div>
					<h2>show-{this.props.store.count}-{this.props.store.doubleCount}</h2>
				</div>
			);
	}
}

export default Show;