Recently, I found that RN integrated mobx on the Internet, and installed various outdated plug-ins, but also wrong, I decided to write a simple integration according to the official website.

Reprint to indicate the source oh

Install the configuration

  • @babel/plugin-proposal-decorators // is to fit the decorator format
  • mobx
  • mobx-react

My version here is

"@ Babel/plugin - proposal - decorators" : "7.8.3", "mobx" : "5.15.4", "mobx - react" : "6.1.8."Copy the code

Babelrc is created in the root directory

{
    "presets": [
        "module:metro-react-native-babel-preset"
    ],
    "plugins": [
        [
            "@babel/plugin-proposal-decorators",
            {
                "legacy": true
            }
        ]
    ]
}
Copy the code

integration

  1. Create one/more stores
import { observable, Action} from 'mobx' /** * App store is a system level store that handles app data */ / mobx < 6.0.0 class appstore {@observable num = @observable count = 0 @action setAppName(num:) String) {this.num = num} @action addCount() {this.count++}} // mobx version >=6.0.0 class AppStore {constructor() {// MakeAutoObservable (this)} num = 'I am a random number' count = 0 setAppName(num: string) { this.num = num } addCount() { this.count++ } } export const appStore = new AppStore()Copy the code
  1. Centralized management of multiple stores facilitates initialization
import { appStore } from './store/app.store'

const mainStore = {
  appStore
}

export default mainStore

Copy the code
  1. Initialize (on entry, e.g. 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> ) }Copy the code
  1. use
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=' props' onPress={() => { This. Props. Navigation. Navigate (' Profile ')}} / > < Button title = 'random' onPress = {() = > Enclosing props. AppStore. SetAppName (String (Math) random () * 100))} / > < Button title = {' hits' + this. Props. AppStore. Count} onPress={() => this.props.appStore.addCount()} /> </View> ) } }Copy the code