mobx
react中 全局数据管理库 可以简单的实现数据的跨组件共享 类似 vue中的vuex
使用步骤
-
安装依赖
mobx
核心库mobx-react
方便在react中使用mobx技术的库@babel/plugin-proposal-decorators
让rn
项目支持es7
的装饰器语法的库
yarn add mobx mobx-react @babel/plugin-proposal-decorators
-
在
babel.config.js
添加以下配置plugins: [ ['@babel/plugin-proposal-decorators', { 'legacy': true }] ]
-
新建文件
mobxindex.js
用来存放 全局数据import { observable, action } from "mobx"; class RootStore { // observable 表示数据可监控 表示是全局数据 // es7的装饰器语法 Object.defineProperty @observable name = "hello"; // action行为 表示 changeName是个可以修改全局共享数据的方法 @action changeName(name) { this.name = name; } } export default new RootStore();
-
在根组件中挂载app.js
通过
Provider
来挂载和传递import React, { Component } from 'react'; import { View} from 'react-native'; import rootStore from "./mobx"; import { Provider} from "mobx-react"; class Index extends Component { // 正常 render() { return ( <View > <Provider rootStore={rootStore} > <Sub1></Sub1> </Provider> </View> ); } }
-
其他组件中使用
import React, { Component } from 'react'; import { View, Text } from 'react-native'; import {inject,observer } from "mobx-react"; //通过observer观察改变,触发render @inject("rootStore") // 注入 用来获取 全局数据的 @observer // 当全局发生改变了 组件的重新渲染 从而显示最新的数据 class Sub1 extends Component { changeName = () => { // 修改全局数据 this.props.rootStore.changeName(Date.now()); } render() { console.log(this); //this.props下面可以找到全局数据 return ( <View><Text onPress={this.changeName}>{this.props.rootStore.name}</Text></View> //输出"hellow" ); } } export default Index;