store.js
import {observable, computed, action} from 'mobx';
class userStoreClass {
@observable user = {
name: 'admin',
role: '管理员'
};
count = 0;
@computed get userName(){
return this.user.name;
}
@action changeUser(){
if(this.count % 2 === 1){
this.user = {
name: 'admin',
role: '管理员'
};
}else{
this.user.name = 'guest';
this.user.role = '访客';
this.user.isGuest = 'true';
}
this.count ++;
}
}
const userStore = new userStoreClass();
export default userStore;
使用Provider传递store的方式为:
import {Provider} from 'mobx-react';
import userStore from './models/userStore';
import App from './components/App';
App.js
import React, {Component} from 'react';
import {inject, observer} from 'mobx-react';
@inject( 'store')
@observer
export default class User extends Component{
state={
userChangeTimes: 0
}
change=()=>{
this.props.store.changeUser()
let {userChangeTimes} = this.state;
userChangeTimes ++ ;
this.setState({userChangeTimes});
}
render(){
// 可以以this.props.userStore形式获取store内state
const {user} = this.props.store;
// 以.形式使用对象的属性值
return(
name:{user.name}
role:{user.name}
{user.isGuest ? `isGuest:${user.isGuest}` : ''}
);
}
}