mobx在react中是全局數(shù)據(jù)管理庫,相當于vue中的vuex
當前使用的版本
react版本號
16.13.1
react-native版本號
0.63.3
mobx版本號
^6.0.4
mobx-react版本號
^7.0.5
使用步驟
- 安裝依賴
- mobx 核心庫
- mobx-react 方便在react中使用mobx技術的庫
- @babel/plugin-proposal-decorators
yarn add mobx mobx-react @babel/plugin-proposal-decorators
- 在babel.config.js添加一下配置
plugins:[
['@babel/plugin-proposal-decorators',{'legacy':true}]
]
- 新建文件mobx/index.js用來存放全局數(shù)據(jù)
//無需通過observable和action等修飾器,直接在構造函數(shù)中使用makeAutoObservable來實現(xiàn)observable和action修飾器功能,使代碼更加簡潔。
import {makeAutoObservable} from 'mobx';
class RootStore{
constructor(){
makeAutoObservable(this)
}
name='lee';
changeName(name){
this.name=name
}
}
export default new RootStore()
- 在項目目錄下index.js文件中掛載
通過provider來掛載和傳遞
import { AppRegistry } from 'react-native';
import { name as appName } from './app.json';
import { Provider } from 'mobx-react';
import RootStore from './mobx/index';
import Com from './view/Com'
// 調試network請求的
global.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || global.XMLHttpRequest
import React, { Component } from 'react'
export default class Index extends Component {
render() {
return (
<Provider RootStore={RootStore}>
<Com />
</Provider>
)
}
}
AppRegistry.registerComponent(appName, () => Index);
- 在view/Com.js類組件中如何使用mobx
import React, { Component } from 'react'
import { Button, SafeAreaView, StatusBar, Text, View } from 'react-native'
import { inject, observer } from 'mobx-react'
@inject('RootStore')
@observer
class Com extends Component {
constructor(props) {
super(props)
}
handChageName=()=>{
this.props.RootStore.changeName('張三')
}
render() {
let {name} =this.props.RootStore;
console.log(name)
return (
<>
<StatusBar barStyle='light-content'></StatusBar>
<SafeAreaView style={{ backgroundColor: 'blue' }}>
<View style={{ height: '100%', backgroundColor: 'white' }}>
<Text onPress={this.handChageName} >修改</Text>
<Text>{name}11</Text>
</View>
</SafeAreaView>
</>
)
}
}
export default Com
在view/Com.js函數(shù)組件中如何使用mobx
import { Button, SafeAreaView, StatusBar, Text, View } from 'react-native';
import {inject,observer} from 'mobx-react';
function Com(props) {
let {name}=props.RootStore
return (
<View className="App">
<Text>{name}</Text>
</View>
);
}
export default inject('RootStore')(observer(Com));