ReactNativeHybrid开发

react-native使用mobx全局状态管理

2019-01-17  本文已影响123人  蜗牛的学习方法

1、初始化react-native项目

react-native init mobxnative

2、下载mobx 插件

npm i mobx mobx-react --save

3、配置装饰器插件

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

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


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里面:


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 (
      <Provider store={AppStore}>
        <Home/>
      </Provider>
    );
  }
}
const styles = StyleSheet.create({
});

引用页面:


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 (
        <View style={styles.container}>
            <TouchableOpacity onPress={this.sub}>
                <Text>-</Text>  
            </TouchableOpacity>
            <TextInput style={{width:100,height:35,borderWidth:1}} value={store.counter.toString()}/>
            <TouchableOpacity onPress={this.add}>
                <Text>+</Text>  
            </TouchableOpacity>   
        </View>
        );
    }
}

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

完整目录结构:


WX20190117-141605.png
上一篇下一篇

猜你喜欢

热点阅读