哈瑞养生
您的当前位置:首页React Native中Mobx的使用方法详解

React Native中Mobx的使用方法详解

来源:哈瑞养生


MobX 是一款精准的状态管理工具库,对我来说非常容易学习和接受。我在 React 和 React Native 应用中使用过 Flux、Alt、Redux 和 Reflux,但我会毫不犹豫地说,MobX 的简单性立即成为了我最喜欢的状态管理工具。我期望能将它运用在未来的项目中,并且对 MobX 的发展拭目以待。

任何源自应用状态的东西都应该自动地获得。其中包括UI、数据序列化、服务器通讯,等等。

上官网的图

  

环境我就不配了,官网给了详细的教程,我的环境是RN+TS,这里需要特别注意一下,由于Mobx要用的装饰器,如果单纯的用create-react-app安装好环境后,一定要特别特别注意:

此时使用@observable是不行的,因为不支持装饰器语法,

此问题有两种解决方案:1.在当前环境中设置支持装饰器,

           下面是官网的详细配置链接,https://cn.mobx.js.org/best/decorators.html

            2.使用MobX的内置的 decorate  工具在不支持装饰器语法的情况加使用

接下来下面给你吃,不是,下面我用一个小例子来演示一下,Go,Go,Go(注意,我这里面默认装饰器是可用的,因为我环境配好了已经)

1.yarn add mobx 

2.首先我们状态管理肯定会有一个仓库吧,那我们来建一个仓库,(注意:我创建了两个小的分支,因为状态管理总不可能怼到一个文件里面吧)

首先上一手仓库的结构

 

home.tsx的代码  

注意:1. 从mobx中引入observable,action

   2.用装饰器修饰仓库的数据  

   3.导出时需要new一下    

import { observable, action } from 'mobx'


class List {
 @observable isShowMap: boolean = false

 @action
 switchTab (info: boolean) {
 this.isShowMap = info
 }
}

export default new List()

list.tsx的代码

  注意:1.此处多加入了runInAction,不加此属性当然也可以,但是就不会记录时间旅行了

import { observable, action, runInAction } from 'mobx'

class List {
 @observable listData: Array<any> = []

 @action
 getListData () {
 fetch('https://ik9hkddr.qcloud.la/mock/cookbook-list.json')
 .then(reponse => reponse.json())
 .then(result => {
 runInAction(() => {
 this.listData = result.data
 })
 })
 }
}

export default new List()

index.js的代码

  注意:在此处将两个树枝里面的数据都引入,合并到一起

import list from './list'
import home from './home'
const store = { list, home }
export default store

3.将仓库绑定到根组件上

     注意:在此引入Provider将仓库和根组件绑定

import React from 'react'
 import { Provider } from 'mobx-react'
 import Home from './pages/home/Home'
 import HotList from './pages/hotlist/HotList'
 import store from './store' 

export default class componentName extends React.Component {
 render() {
 return (
 <Provider store={store}>
 <RootStack></RootStack>
 </Provider>
 )
 }
}}

4.最后一步,在组件中引用仓库里的数据,并可以修改仓库里的数据

  注意:1.引入observer和inject,将组件和仓库连接起来,类似于在React中使用react-redux中的connnect方法

import React from 'react'
import { observer, inject } from 'mobx-react'
import {
 View,
 Text,
} from 'react-native'

interface Props {
}
interface State {
}
//此处时引用最重要的步骤用inject和observer
@inject('store')
@observer
export default class Home extends React.Component<Props, State> {
 render () {
 return (
 <View>
 {/* 引用store里面储存的值 */}
 <Text>{this.props.store.home.isShowMap}</Text>
 </View>
 )
 }
 componentDidMount () {
 //调用函数修改store里面的值
 this.props.store.home.switchTab(value)
 }
}

到这里,今天的随笔已经结束了,可能写的不是那木有条理,若有错误还往各位同学指出,我嗓子已经说不出话来了,所以在这提醒各位同学

 学技术的同时一定要记得锻炼身体,我的天,少吃饭多吃药,多打代码多保健,活着最重要!

 总结

显示全文