1. 安装依赖
cnpm i -S mobx mobx-react
2. 创建store/index.js
import {observable, computed, action , makeObservable} from "mobx";
class Store {
constructor() {
makeObservable(this)
}
@observable num = 0
@computed get getNumDouble(){
return this.num * 2
}
@action setNum(num){
this.num = num
}
}
export default new Store()
3. app.js 使用Provider 包裹
import './App.css';
import Index from "./router/Index";
import {Provider} from "mobx-react";
import Store from "./store/index.js";
function App() {
return (
<div className="App">
<Provider store={Store}>
<Index></Index>
</Provider>
</div>
);
}
export default App;
4. 状态显示、修改
import React from "react";
import {inject , observer} from "mobx-react";
@inject("store")
@observer
class Page1 extends React.Component{
render() {
return <div>
数值:{this.props.store.getNumDouble}
<button onClick={this.handleChange}>修改数值</button>
</div>
}
handleChange =()=>{
this.props.store.setNum(10)
}
}
export default Page1
|