加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react-native+MobX

发布时间:2020-12-15 20:36:50 所属栏目:百科 来源:网络整理
导读:参考https://segmentfault.com/a/1190000014165693同事解决其发生的问题 1.版本 "mobx": "4.3.1", "mobx-react": "5.1.0", 否则会报错 2.安装 yarn add babel-plugin-transform-decorators-legacy yarn add babel-preset-react-native-stage-0 yarn add babe
参考https://segmentfault.com/a/1190000014165693同事解决其发生的问题
1.版本
"mobx": "4.3.1",
"mobx-react": "5.1.0",
否则会报错


2.安装
yarn add babel-plugin-transform-decorators-legacy
yarn add babel-preset-react-native-stage-0
yarn add babel-plugin-transform-runtime

3.创建store文件夹,并在下面创建几个js文件



// home import { observable,action } from "mobx"; class HomeStore { @observable text; // 注册变量,使其成为可检测的 @observable num; constructor() { this.num = 0; // 初始化变量,可以定义默认值 this.text = "Hello,this is homePage!!!"; } @action // 方法推荐用箭头函数的形式 plus = () => { this.num += 1; }; @action minus = () => { this.num -= 1; }; } const homeStore = new HomeStore(); export { homeStore };

4.在store文件夹下创建一个index.js文件将刚刚创建的两个js文件引入到里面// user import { observable,action } from "mobx"; class UserStore { @observable userInfo; @observable text; constructor() { this.userInfo = "123"; this.text = "Hello,this is UserPage!!!"; } @action getListData = () => { fetch(`http://yapi.demo.qunar.com/mock/5228/record/list`) .then( action("fetchRes",res => { return res.json(); }) ) .then( action("fetchSuccess",data => { return (this.userInfo = data); }) ) .catch( action("fetchError",e => { console.log(e.message); }) ); }; }
import { homeStore } from "./home";
import { userStore } from "./user";
const store = { homeStore,userStore};

export default store;

5.在App.js中将其引入
import React,{Component} from ‘react‘;
import {Provider} from ‘mobx-react‘;
import AppStackNavigator from "./Router";
import store from ‘./store‘;
export default class App extends Component{
render(){
return (
<Provider {...store}>
<AppStackNavigator></AppStackNavigator>
</Provider>
)
}
}

6.调用状态机
import {observer,inject} from ‘mobx-react‘;
@inject(‘homeStore‘) @observer;
<Text>状态管理器</Text><Text>{this.props.homeStore.name}</Text><Text>{this.props.homeStore.msg}</Text>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读