<
Mobx-react
>
上一篇

面试问题大集合 巴拉巴拉
下一篇

React-native 练手项目
关于mobx的使用

官方文档 点击查看

个人Demo 点击查看

基本用法:

  1. store中定义全局变量+ 方法
  2. 项目中使用设置
  3. 组件引用store

1.store/index.js中定义全局变量+ 方法

import{ observable, action, computed} from 'mobx';
import monment from 'moment';

class AppStore{
    @observable time = '2019';
    @observable todos = [];
    @computed get desc(){
        return `${this.time}还有${this.todos.length}条任务等待完成`
    }
    @action addTodo(todo){
        this.todos.push(todo);
    }
    @action deleteTodo(todo){
        this.todos.pop(todo);
    }
    @action reasetTodo(){
        this.todos = [];
    }
    @action getNow(){
        this.time = monment().format('YYYY/MM/DD HH:mm:ss');
    }
}
const store = new AppStore();
setInterval (()=>{
    store.getNow()
},1000)

export default store;

2.项目中使用设置

import React from 'react'
import { Provider } from 'mobx-react';  //API
import  Home from './pages/Home';
import  store  from './store/index';

function App() {
  return (
    <div> 
      <Provider store = {store}>
        <Home />
      </Provider>
    </div>
  );
}

export default App;

3.组件引用store

import React, { Component } from 'react';
import { inject, observer } from "mobx-react";
import './index.css';

@inject('store') @observer
class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {  }
    }
    handleTodos(res){
        let {store} = this.props;
        switch(res){
            case 'addOne': 
                store.addTodo("新加项目")
                break;
            case 'deleteOne': 
                store.deleteTodo()
                break;
            case 'deleteAll':  
                store.reasetTodo()
                break;
            default:
        }
    }

    render() { 
        let { store } = this.props
        return (  
            <div className='home'>
                <h1>在Reac中使用Mobx</h1>
                <div>{store.desc}</div>
                <button 
                    className='button'
                    onClick = {this.handleTodos.bind(this,'addOne')}
                >
                    添加一条
                </button>
                <button
                    className='button'
                    onClick = {this.handleTodos.bind(this,'deleteOne')}
                >
                    删除一条
                </button>
                <button 
                    className='button'
                    onClick = {this.handleTodos.bind(this,'deleteAll')}
                >
                    删除所有
                </button>
                <div>
                    <ul>
                    {store.todos.map((item,index,arr)=>{
                        return <p key={item+index}>{item}</p>
                    })}
                    </ul>
                </div>
            </div>
        );
    }
}
 
export default Home;
Top
Foot