Mobx

370 阅读1分钟

基础使用

Mobx

安装

# Mobx 支持
npm install mobx mobx-react -S
# 装饰器支持
npm install @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties -D

修改配置

git add .  # 提交代码
git commit -m'提交说明'

yarn run eject  Y  # 打散配置

配置

package.json

"babel": {
    "presets": [
      "react-app"
    ],
    "plugins": [
      [
        "@babel/plugin-proposal-decorators",
        {
          "legacy": true
        }
      ],
      [
        "@babel/plugin-proposal-class-properties",
        {
          "legacy": true
        }
      ]
    ]
  },

状态管理

import {
    observable, action, computed
} from 'mobx'

class AppStore {
    @observable time= '时间'
    @observable todos = ['1','2','3']

    @action addTodo(todo){
        this.todos.push(todo)
        /**
         * 业务页面调用
         * this.props.store.addTodo('abc')
         * 
         * */ 
    }
    //  当 time 值改变 changeTime 会重新执行,返回新的值
    @computed get changeTime(){
        return this.time 
    }
}

const store = new AppStore()

//  外部改变time
/**
 * store.addTodo('abc')
 * 
*/
export default store

APP.js

import React from 'react';
import { Provider } from 'mobx-react'
import store from './store'

import Home from './home.jsx'
import './App.css';

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

export default App;

Home.js

import React, { Component } from 'react'
import { inject, observer } from 'mobx-react'

@inject('store') @observer
 class Home extends Component {
    constructor(props){
        super(props)
        this.state = {

        }
    }
    render() {
        let { store } = this.props
        return (
            <div>
                <p>{store.time}</p>
                <ul>
                    {store.todos.map((item,index) => {
                        return (
                        <li key={index}>{item}</li>
                        )
                    }) }
                </ul>
            </div>
        )
    }
}

export default Home;