react-native+MobX

令狐宜民
2023-12-01
参考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

防止@无法识别
touch .babelrc
{
 'presets': ['react-native'],
 'plugins': ['transform-decorators-legacy']
}


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 };


// 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); }) ); }; }
4.在store文件夹下创建一个index.js文件将刚刚创建的两个js文件引入到里面
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>

 

转载于:https://www.cnblogs.com/boonook/p/10234440.html

 类似资料: