react-native+mobx

最近發(fā)現(xiàn)網(wǎng)上RN集成mobx各種花樣,安裝各種過期插件,還都不對,我決定自己寫一個,照著官網(wǎng)很簡單的集成好了。

轉(zhuǎn)載注明出處哦

安裝配置

  • @babel/plugin-proposal-decorators // 是為了適配裝飾器格式
  • mobx
  • mobx-react

我這里的版本是

"@babel/plugin-proposal-decorators": "7.8.3",
"mobx": "5.15.4",
"mobx-react": "6.1.8",

根目錄下創(chuàng)建.babelrc

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

集成

  1. 創(chuàng)建一個/多個store
import { observable, action } from 'mobx'

/**
 * appstore為系統(tǒng)級store,用來處理app的常規(guī)數(shù)據(jù)
 */
// mobx 版本 < 6.0.0
class AppStore {
  @observable num = '我是隨機數(shù)'

  @observable count = 0

  @action
  setAppName(num: string) {
    this.num = num
  }

  @action
  addCount() {
    this.count++
  }
}

// mobx 版本>=6.0.0
class AppStore {
    constructor() {
        // 建議使用這種方式,自動識別類型,不需要再加前綴
        makeAutoObservable(this)
    }
  num = '我是隨機數(shù)'
  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 (
    <Provider {...mainStore}>
      <NavigationContainer>
        <TabScreen />
      </NavigationContainer>
    </Provider>
  )
}

  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<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='隨機數(shù)'
          onPress={() => this.props.appStore.setAppName(String(Math.random() * 100))}
        />
        <Button
          title={'點擊數(shù)' + this.props.appStore.count}
          onPress={() => this.props.appStore.addCount()}
        />
      </View>
    )
  }
}

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容