react-native04:使用mobx全局状态管理

1、初始化react-native项目

react-native init mobxnative

2、下载mobx 插件

npm i mobx mobx-react --save
//mobx和core版本不能使用最新的版本,会出现问题导致项目运行不起来,下面的版本是能正常运行的版本,我的最新使用的react-native版本是0.59.9
"mobx": "^5.9.4",
"mobx-react": "^5.4.3",
"@babel/core": "^7.4.0",

3、配置装饰器插件

//bable 7.0
yarn add  @babel/plugin-proposal-decorators --save
//在项目的.babelrc或者是babel.config.js文件下配置:
"plugins": [
    [
      "@babel/plugin-proposal-decorators",
      {
        "legacy": true
      }
    ]
  ]

4、在项目目录下建一个Mobx文件夹,里面新建一个appStore.js


react-native04:使用mobx全局状态管理_第1张图片
WX20190117-141244.png

代码:

import {observable,action} from 'mobx';
var appStore = observable({
    counter: 0
});
appStore.addCount = action(()=>{
    appStore.counter+=1;
});
appStore.subCount = action(()=>{
    if(appStore.counter<=0){
        return;
    }
    appStore.counter-=1;
});
appStore.changeCount = action((key)=>{
    if(key<=0){
        appStore.counter=0;
    }
    appStore.counter=parseInt(key);
});
export default appStore

在项目底层app.js里面:


react-native04:使用mobx全局状态管理_第2张图片
WX20190117-141234.png
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import {Provider} from 'mobx-react'
import AppStore from './src/Mobx/appStore'
import Home from './src/pages/home'

export default class App extends Component{
  render() {
    return (
      
        
      
    );
  }
}
const styles = StyleSheet.create({
});

引用页面:


react-native04:使用mobx全局状态管理_第3张图片
WX20190117-141257.png
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View,TouchableOpacity,TextInput} from 'react-native';
import {observer, inject} from 'mobx-react';

@inject('store')
@observer
export default class Home extends Component{
    constructor(props){
        super(props);
        this.state={
            value:0
        }
    }
    componentWillMount(){
        console.log(this.props.store.counter)
    }
    sub=()=>{
        let {store}=this.props;
        store.subCount()
    }
    add=()=>{
        let {store}=this.props;
        store.addCount()
    }
    render() {
        let {store}=this.props
        return (
        
            
                -  
            
            
            
                +  
               
        
        );
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1,
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center'
    }
});

mobx的另一种写法:

class appStore{
    @observable counter = 0;
    @observable themeType = 'light';
    @observable theme=themeData['light'];
    @action changeTheme=(themeType)=>{
        this.themeType=themeType
        this.theme=themeData[themeType];
    }
}
export default new appStore();

完整目录结构:


react-native04:使用mobx全局状态管理_第4张图片
WX20190117-141605.png

你可能感兴趣的:(react-native04:使用mobx全局状态管理)