基本用法
定义store
。store
主要包含如下三部分内容:import { observable, action, computed } from "mobx";
- state:数据状态,
@observable userInfo = {}
; - action:动作函数,是唯一可以修改state的函数,
@action getUserInfo() {}
- computed:纯函数,不修改state,只是获得state,
@computed get userName() { return ‘xxx’;}
将store注入整个router下:import { Provider } from "mobx-react";
import User from '../store/User'
const store = {User}
<Provider {…store}>{router}</Provider>
在页面中使用:import { inject, observer } from "mobx-react";
- inject:将和页面相关的store注入页面—>
@inpect(‘User')
- observer:页面观察state的变化—>
@observer Component
- 在页面中获得改变后的state:
this.props.User.userInfo
- 在页面中触发action函数:
this.props.User.getUserInfo()
异步action(在严格模式下)
getUserInfo() {
UserRequest.getUserInfo()
.then(res => {
this.userInfo = res.data;
});
}
如上定义会抛出异常,因为 UserRequest.getUserInfo的回调函数不是当前action的一部分,action只作用于定义的当前函数,即setTimeout、promise、async的回调函数如果没有定义在当前函数内部,想要正常执行都必须再用一层action包裹起来,如果定义在当前函数内部,则修改state的地方需要用action包裹起来。
- 第一种
getUserInfo() {
UserRequest.getUserInfo()
.then(action(res => {
this.userInfo = res.data;
}));
}
- 第二种
@action
getUserInfo() {
UserRequest.getUserInfo()
.then(this.setUserInfo);
}
@action
setUserInfo({data}) {
this.userInfo = data;
}
- 第三种
@action
getUserInfo() {
UserRequest.getUserInfo()
.then(res => {
const data = res.data;
action(() => {
this.userInfo = data;
});
});
}
使用注意事项
- 修改store中的值不会触发componentWillReceiveProps生命周期函数;
- 建议在componentWillUpdate和conponentDidUpdate中获取状态改变,但是试了后也没成功捕捉到变化;