react-native+mobx

最近发现网上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
            }
        ]
    ]
}

集成

  1. 创建一个/多个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()

  1. 把多个store集中管理,便于初始化
import { appStore } from './store/app.store'

const mainStore = {
  appStore
}

export default mainStore

  1. 初始化(在入口处,比如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 (
    
      
        
      
    
  )
}

  1. 使用
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 {
  render() {
    return (
      
        Home!
        {this.props.appStore.num}
        

你可能感兴趣的:(react-native+mobx)