React-Native + Mobx一步步构建项目

前端之家收集整理的这篇文章主要介绍了React-Native + Mobx一步步构建项目前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

前言

前提是你已经搭好环境,并且能跑起来;
否则的话先进行:Mac环境搭建,目标:ios

本项目使用的依赖:

  1. "dependencies": {
  2. "lodash": "^4.17.5","mobx": "^4.1.0","mobx-react": "^5.0.0","native-base": "^2.3.5","react": "^16.3.0-alpha.1","react-native": "0.54.4","react-navigation": "^1.5.8"
  3. },

准备工作

1. 安装相应依赖:mobx 和 mobx-react;

  1. npm i mobx mobx-react --save

2. 安装一些 babel 插件,以支持 ES7 的 decorator 特性:

  1. npm i babel-plugin-transform-decorators-legacy babel-preset-react-native-stage-0 --save-dev

3. 打开 .babelrc 没有就创建一个,配置 babel 插件:

  1. touch .babelrc

写入:

  1. {
  2. 'presets': ['react-native'],'plugins': ['transform-decorators-legacy']
  3. }

补充:ES7装饰器语法在编译器可能会报错;我这里用的是vscode,分享解决办法:

@H_403_31@
  • 找到 首选项 > 设置 > 工作区设置;
  • 加入以下代码
    1. "javascript.implicitProjectConfig.experimentalDecorators": true

    至此准备工作已经差不多了,接下来写代码。。。


    加入Mobx

    1. 根目录下新建 js文件夹; js下新建store文件夹;

    2. store下新建index.js 作用是合并每个store到一个store中去,最终通过 <Provider {...store}>方式注入<App/>;

    3.分别在store下新建几个js,示例:

    1. // home
    2. import { observable,action } from "mobx";
    3.  
    4. class HomeStore {
    5. @observable text; // 注册变量,使其成为可检测的
    6. @observable num;
    7.  
    8. constructor() {
    9. this.num = 0; // 初始化变量,可以定义默认值
    10. this.text = "Hello,this is homePage!!!";
    11. }
    12.  
    13. @action // 方法推荐用箭头函数的形式
    14. plus = () => {
    15. this.num += 1;
    16. };
    17.  
    18. @action
    19. minus = () => {
    20. this.num -= 1;
    21. };
    22. }
    23.  
    24. const homeStore = new HomeStore();
    25.  
    26. export { homeStore };
    1. // user
    2. import { observable,action } from "mobx";
    3.  
    4. class UserStore {
    5. @observable userInfo;
    6. @observable text;
    7.  
    8. constructor() {
    9. this.userInfo = "123";
    10. this.text = "Hello,this is UserPage!!!";
    11. }
    12.  
    13. @action
    14. getListData = () => {
    15. fetch(`http://yapi.demo.qunar.com/mock/5228/record/list`)
    16. .then(
    17. action("fetchRes",res => {
    18. return res.json();
    19. })
    20. )
    21. .then(
    22. action("fetchSuccess",data => {
    23. return (this.userInfo = data);
    24. })
    25. )
    26. .catch(
    27. action("fetchError",e => {
    28. console.log(e.message);
    29. })
    30. );
    31. };
    32. }
    33.  
    34. const userStore = new UserStore();
    35.  
    36. export { userStore };

    4. 通过index文件合并:

    1. import { homeStore } from "./home";
    2. import { saleStore } from "./sale";
    3. import { userStore } from "./user";
    4.  
    5. const store = { homeStore,saleStore,userStore };
    6.  
    7. export default store;

    5. 在组件中使用Mobx:

    js目录下新建tabs文件夹,新建HomeScreen.js

    1. import React,{ Component } from "react";
    2. import { View,Text,StyleSheet,TouchableOpacity } from "react-native";
    3. import { connect } from "mobx-react";
    4. import { observer,inject } from "mobx-react";
    5. import { Button,Container } from "native-base";
    6. import Headers from "../common/components/header";
    7.  
    8. @inject(["homeStore"]) // 注入对应的store
    9. @observer // 监听当前组件
    10. class HomeScreen extends Component {
    11. constructor(props) {
    12. super(props);
    13. this.store = this.props.homeStore; //通过props来导入访问已注入的store
    14. this.state = {
    15. };
    16. }
    17.  
    18. render() {
    19. const { text,num } = this.store;
    20. return (
    21. <Container>
    22. <Headers
    23. title="首页"
    24. type='index'
    25. navigation={this.props.navigation}
    26. />
    27. <Text>{text}</Text>
    28. <Button primary onPress={() => this.store.plus()}>
    29. <Text>add</Text>
    30. </Button>
    31. <Text>{num}</Text>
    32. <Button primary onPress={() => this.store.minus()}>
    33. <Text>Minu</Text>
    34. </Button>
    35. </Container>
    36. );
    37. }
    38. }
    39.  
    40. export default HomeScreen;
    41.  
    42. const styles = StyleSheet.create({
    43. container: {
    44. flex: 1,justifyContent: "center",alignItems: "center",backgroundColor: "#F5FCFF"
    45. }
    46. });

    6. 目前组件中还拿不到当前组件的store,接下来注入store

    在初始化的项目结构中,项目运行的入口文件index.js,注册了同级目录下的App.js;

    1. // index.js
    2.  
    3. import { AppRegistry } from 'react-native';
    4. import App from './App';
    5.  
    6. AppRegistry.registerComponent('demo',() => App);

    由于需要在App.js上套入store 所以改写结构,

    1. js文件夹下新建App.js

    touch App.js

    可以把根目录下App.js内容copy过来,然后删掉根目录下App.js文件;

    2. js目录下新建 setup.js 文件
    1. import React from "react";
    2. import { Provider } from "mobx-react";
    3. import App from "./App";
    4. import store from "./store";
    5.  
    6. export default function setup() {
    7. class Root extends React.Component {
    8. render() {
    9. return (
    10. <Provider {...store}>
    11. <App />
    12. </Provider>
    13. );
    14. }
    15. }
    16. return Root;
    17. }
    3. 修改index启动页代码
    1. import { AppRegistry } from 'react-native';
    2. import setup from "./js/setup";
    3.  
    4. AppRegistry.registerComponent('******',() => setup());

    现在store已经注入,在每个组件中也可以拿到当前store的数据了;可以进行代码开发了;

    猜你在找的React相关文章