安装
- npm install mobx --save
- npm install mobx-react --save(React绑定库)
使用
import { message } from "antd";
import { makeAutoObservable, computed, action, runInAction } from "mobx";
import api from '../services' //通常在services文件中封装接口方法
class Person{
name ="xx";
age = 22;
skill = "fly";
pending = true;
content = '';
constructor(){
makeAutoObservable(this)
}
@action
async getList(params){
try {
this.pending = true;
const res = await api.test.getList(params)
runInAction(()=>{
this.pending = false;
this.content = res.content
})
} catch (error) {
runInAction(()=>{
message.error('error')
this.pending = false;
})
}
}
}
const person = new Person
export default person
- 然后在store的根文件(index.js)中引用;
import test from './person';
const stores = {
person
}
export default stores;
import { Provider } from 'mobx-react';
import stores from './store';
<Provider {...stores}>
<div></div>
</Provider>
import { observer, inject } from 'mobx-react'
const TableBox = (props.any) => {
const { person } = props;
return(
<div>
<p>{person.name}</p>
</div>
)
}
export default inject('project')(observer(TableBox))