最近发现网上RN集成mobx各种花样,安装各种过期插件,还都不对,我决定自己写一个,照着官网很简单的集成好了。
转载注明出处哦
安装配置
- @babel/plugin-proposal-decorators // 是为了适配装饰器格式
- mobx
- mobx-react
我这里的版本是
"@babel/plugin-proposal-decorators": "7.8.3",
"mobx": "5.15.4",
"mobx-react": "6.1.8",
根目录下创建.babelrc
{
"presets": [
"module:metro-react-native-babel-preset"
],
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
]
}
集成
- 创建一个/多个store
import { observable, action } from 'mobx'
/**
* appstore为系统级store,用来处理app的常规数据
*/
// mobx 版本 < 6.0.0
class AppStore {
@observable num = '我是随机数'
@observable count = 0
@action
setAppName(num: string) {
this.num = num
}
@action
addCount() {
this.count++
}
}
// mobx 版本>=6.0.0
class AppStore {
constructor() {
// 建议使用这种方式,自动识别类型,不需要再加前缀
makeAutoObservable(this)
}
num = '我是随机数'
count = 0
setAppName(num: string) {
this.num = num
}
addCount() {
this.count++
}
}
export const appStore = new AppStore()
- 把多个store集中管理,便于初始化
import { appStore } from './store/app.store'
const mainStore = {
appStore
}
export default mainStore
- 初始化(在入口处,比如app.tsx, index.js)
import * as React from 'react'
import { NavigationContainer } from '@react-navigation/native'
import TabScreen from './src/page/tabs/tab.screen'
import { Provider } from 'mobx-react'
import mainStore from './src/mobx/mainStore'
export default function App() {
return (
<Provider {...mainStore}>
<NavigationContainer>
<TabScreen />
</NavigationContainer>
</Provider>
)
}
- 使用
import React from 'react'
import { View, Text, Button } from 'react-native'
import { observer, inject } from 'mobx-react'
interface IP {
appStore?: any
navigation?: any
}
interface IS {}
@inject('appStore')
@observer
export default class HomeScreen extends React.Component<IP, IS> {
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Home!</Text>
<Text>{this.props.appStore.num}</Text>
<Button
title='去个人中心'
onPress={() => {
this.props.navigation.navigate('Profile')
}}
/>
<Button
title='随机数'
onPress={() => this.props.appStore.setAppName(String(Math.random() * 100))}
/>
<Button
title={'点击数' + this.props.appStore.count}
onPress={() => this.props.appStore.addCount()}
/>
</View>
)
}
}