官方文档 点击查看
个人Demo 点击查看
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;
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;
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;